Question

I'm using String.split() to divide some Strings as IPs but its returning an empty array, so I fixed my problem using String.substring(), but I'm wondering why is not working as intended, my code is:

// filtrarIPs("196.168.0.1 127.0.0.1 255.23.44.1 100.168.100.1 90.168.0.1","168");
public static String filtrarIPs(String ips, String filtro) {
    String resultado = "";
    String[] lista = ips.split(" ");
    for (int c = 0; c < lista.length; c++) {
        String[] ipCorta = lista[c].split("."); // Returns an empty array
        if (ipCorta[1].compareTo(filtro) == 0) {
            resultado += lista[c] + " ";
        }
    }
    return resultado.trim();
}

It should return an String[] as {"196"."168"."0"."1"}....

Was it helpful?

Solution 3

Your statement

lista[c].split(".")

will split the first String "196.168.0.1" by any (.) character, because String.split takes a regular expression as argument.

However, the point, why you are getting an empty array is, that split will also remove all trailing empty Strings in the result.

For example, consider the following statement:

String[] tiles = "aaa".split("a");

This will split the String into three empty values like [ , , ]. Because of the fact, that the trailing empty values will be removed, the array will remain empty [].

If you have the following statement:

String[] tiles = "aaab".split("a");

it will split the String into three empty values and one filled value b like [ , , , "b"] Since there are no trailing empty values, the result remains with these four values.

To get rid of the fact, that you don't want to split on every character, you have to escape the regular expression like this:

lista[c].split("\\.")

OTHER TIPS

split works with regular expressions. '.' in regular expression notation is a single character. To use split to split on an actual dot you must escape it like this: split("\\.").

Use

String[] ipCorta = lista[c].split("\\.");

in regular expressions the . matches almost any character. If you want to match the dot you have to escape it \\..

String.split() takes a regular expression as parameter, so you have to escape the period (which matches on anything). So use split("\\.") instead.

THis may help you:

 public static void main(String[] args){
    String ips = "196.168.0.1 127.0.0.1 255.23.44.1 100.168.100.1 90.168.0.1";
    String[] lista = ips.split(" ");
    for(String s: lista){
        for(String s2: s.split("\\."))
            System.out.println(s2);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top