[英]Java string split function acting strange
我在Java中使用split()
方法時注意到奇怪的行為。
我有一個字符串如下: 0|1|2|3|4|5|6|7|8|9|10
String currentString[] = br.readLine().split("\\|");
System.out.println("Length:"+currentString.length);
for(int i=0;i < currentString.length;i++){
System.out.println(currentString[i]);
}
這將產生預期的結果:
Length: 11
0
1
2
3
4
5
6
7
8
9
10
但是,如果我收到字符串: 0|1|2|3|4|5|6|7|8||
我得到以下結果:
Length: 8
0
1
2
3
4
5
6
7
8
省略了最后的2個容器。 我需要保留空箱。 不知道我做錯了什么。 我也嘗試過以這種方式使用拆分。 ... split("\\\\|",-1);
但是返回長度為1的整個字符串。
任何幫助將不勝感激!
拆分的默認行為是不返回空標記(因為零限制)。 使用限制為-1的兩個參數split方法將在返回時為您提供所有空標記。
更新:
測試代碼如下:
public class Test {
public static void main(String[] args) {
String currentString[] = "0|1|2|3|4|5|6|7|8||".split("\\|", -1);
System.out.println("Length:"+currentString.length);
for(int i=0;i < currentString.length;i++){ System.out.println(currentString[i]); }
}
}
輸出如下:
Length:11
0
1
2
3
4
5
6
7
8
--- BLANK LINE --
--- BLANK LINE --
“--- BLANK LINE - ”由我輸入,表明返回為空白。 8 |之后空標記為空白一次 並且一次用於最后一個|之后的空尾隨令牌。
希望這可以解決問題。
我的Java有點生疏,但不應該是:
String currentString[] = "0|1|2|3|4|5|6|7|8||".split("\\|");
System.out.println("Length:"+currentString.length);
for(int i = 0; i < currentString.length; i++)
{
System.out.println(currentString[i]);
}
您需要使用indexOf()
然后使用substring()
才能使用它。 我不認為你只能通過使用split()
來清空字符串。
IMO,我認為這是拆分的默認行為,無論如何請試試這個:
String currentString [] = br.readLine()。replace(“||”,“||”)。split(“\\ |”); 的System.out.println( “長:” + currentString.length); for(int i = 0; i <currentString.length; i ++){System.out.println(currentString [i]); }
這尚未經過測試,但我認為這應該可以解決問題。
請檢查以下代碼,我使用了您的解決方案,它的工作原理:
public class SplitTest
{
public static void main(String[] args)
{
String text = "0|1|2|3|4|5|6|7|8||";
String pattern = "\\|";
String [] array = text.split(pattern, -1);
System.out.println("array length:" + array.length);
for(int i=0; i< array.length; i++)
System.out.print(array[i]+ " ");
}
}
輸出是:
array length:11 0 1 2 3 4 5 6 7 8
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.