[英]String.split(String pattern) Java method is not working as intended
我正在使用String.split()將一些字符串划分為IP但它returning an empty array
,所以我使用String.substring()解決了我的問題,但我想知道為什么不按預期工作,我的代碼是:
// 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();
}
它應該返回一個String[] as {"196"."168"."0"."1"}
....
split可以使用正則表達式。 '' 正則表達式表示法是單個字符。 要在實際點上使用拆分拆分,必須將其轉義為: split("\\\\.")
。
你的陳述
lista[c].split(".")
將任意( .
)字符拆分第一個字符串"196.168.0.1"
,因為String.split將正則表達式作為參數。
但是,關鍵是,為什么要獲得一個空數組,該分割還將刪除結果中所有尾隨的空字符串。
例如,請考慮以下語句:
String[] tiles = "aaa".split("a");
這會將String拆分為三個空值,如[ , , ]
。 由於事實,將刪除尾隨空值,該數組將保持為空[]
。
如果您有以下聲明:
String[] tiles = "aaab".split("a");
它會將String拆分為三個空值和一個填充值b
如[ , , , "b"]
,,, [ , , , "b"]
因為沒有尾隨空值,結果將保留這四個值。
為了擺脫這個事實,你不想分裂每個角色,你必須像這樣逃避正則表達式:
lista[c].split("\\.")
String.split()
將正則表達式作為參數,因此您必須轉義句點(與任何內容匹配)。 所以請改用split("\\\\.")
。
這可能對你有所幫助:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.