String. The split (string pattern) Java method did not work as expected
I'm using string Split () divides some strings into IP, but it returns an empty array, so I use string Substring () fixes my problem, but I want to know why it doesn't work as expected. 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 a string [] of {"196". 168 ". 0". 1 "}
Solution
Your statement
lista[c].split(".")
Set any (.) Character splits the first string "196.168.0.1" because string Split takes regular expression as a parameter
However, the key is why you want to get an empty array. This segmentation will also delete 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 null values, such as [,] Due to the fact that trailing null 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 null values and a padding value B, "B"] since there is no trailing null value, the result will retain these four values
In order to get rid of this fact, you don't want to split each character. You must avoid regular expressions like this:
lista[c].split("\\.")