How to get the total empty lines of a text in Android?

I get text from a EditText or part of it, I would like to get the total empty lines, i.e.

Lorem impsum
Lorem impsum

Lorem impsum

The line break, contains \n

How can you get the total of empty lines, in the most efficient way if possible?

It would also be interesting that if an empty line contains white space, tab, which at first glance are not perceived. I assume that performing a pre-line-by-line process and performing a trim would be removed spaces and tabs.

Benchmark results

Loop of 10000 interactions.

  • solution Paul vagas: 845ms
  • SO Solution: 484ms
  • Luiggi Mendoza solution: 84ms
 4
Author: Webserveis, 2016-06-22

4 answers

Based on a previous answer we could get the number of empty lines:

String cadena = " ....... ";
int contadorLineasVacias = 0;
int indice = cadena.indexOf("\n");
//mientras se encuentren saltos de línea
while (indice >= 0) {
    int base = indice;
    int ifinal = cadena.indexOf("\n", indice + 1);
    if (ifinal < 0) {
        break; //no se encontró nuevo salto de línea, detener
    }
    boolean vacio = true;
    for (int i = base + 1; i < ifinal; i++) {
        if (!esCaracterVacio(cadena.charAt(i))) {
            vacio = false;
            break; //detener el for
        }
    }
    if (vacio) {
        contadorLineasVacias++;
    }
    indice = ifinal;
}

This needs a method esCaracterVacio(char) that can be implemented as follows:

public static boolean esCaracterVacio(char c) {
    return c == ' ' || c == '\0' || c == '\t'; //agregar otros caracteres que consideres vacíos
}
 3
Author: Comunidad, 2017-04-13 13:00:52

Assuming you have text in a variable x starting from the following:

Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n
                                  \n
1500s, when an unknown printer took a galley of type and scrambled it to\n 
make a type specimen book. It has survived not only five centuries, but also\n 
\n 
was popularised in the 1960s with the release of Letraset sheets containing\n 
               \n
like Aldus PageMaker including versions of Lorem Ipsum.\n

We have lines with whitespace (which stops being an empty line) , I think your problem could be solved as follows:

String X = " .. "; // Aquí todo el texto que pusimos arriba (ejemplo)
int i = 0; 
int LineasVacias = 0;

while (i + 1 != X.length())
{
    if (X[i] == '\n' && X[i + 1] == '\n') {
        ++LineasVacias; // Si se encuentra que el siguiente caracter está vacio, se incrementa.
        i += 2; continue; // Se salta el siguiente salto de lineay seguimos el bucle.
    }
    else if (X[i] == ' ' && X[i + 1] == ' ') {
        // Si el caracter actual + el siguiente es un espacio en blanco...
        while (X[i] == ' ') ++i; // Se incrementa i, saltando el espacio..
        if (X[i] == '\n') ++LineasVacias;
    }
    ++i;
}

If it is a somewhat dirty and not portable solution, but it has worked for me. I leave you the fiddle (C#) for you to see.

 2
Author: NaCl, 2016-06-22 19:35:13

Here's a solution that includes using a regular expression:

String text = "Lorem impsum\n \nLorem impsum\n \nLorem impsum";
Matcher matcher = Pattern.compile("(?m)^[\\t ]*$").matcher(text);
int count = 0;
while(matcher.find()) {
    count++;
}
System.out.println(count);
 2
Author: Paul Vargas, 2016-06-22 20:30:22

By SO I've found another way to do it

public static int countEmptyLines(String str) {
    final BufferedReader br = new BufferedReader(new StringReader(str));
    String line;
    int empty = 0;
    try {
        while ((line = br.readLine()) != null) {
            if (line.trim().isEmpty()) {
                ++empty;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return empty;
}
 1
Author: Webserveis, 2017-05-23 12:39:21