Java 当分隔符有单引号时,字符串 split() 函数无法按预期工作
Java String split() function not working as expected when delimiter has single quote
我有一个小Java问题,不知道有没有人能快速解答一下?
我正在遍历一个输入字符串,可能是一个名称,其中可能包含一个单引号。当它出现时,我希望能够在循环中使用它。这是一个例子。
String input_string = "some name with o'clock for example";
String[] delims = {" ", "O'", "L'", "D'"};
...
for (String s : delims) {
String[] split_words = input_string.split(delimiter);
for (String word : split_words) {
System.out.println("delimter is " + s);
System.out.println("word is "+ word);
}
}
输出为:
delimter is word is some
delimter is word is name
delimter is word is with
delimter is word is o'clock
delimter is word is for
delimter is word is example
delimter is 'O'' word is some name with o'clock for example
delimter is 'L'' word is some name with o'clock for example
delimter is 'D'' word is some name with o'clock for example
它与 space 配合使用时效果很好,但由于单引号的存在,事情在点钟阶段变得可疑。有什么想法吗?
String.split
区分大小写。它不会围绕您的 "o'"
拆分,因为您已要求它围绕 "O'"
拆分。它与单引号无关。
// This loop prints:
// some name with
// clock for example
for (String s: "some name with o'clock for example".split("o'")) {
System.out.println(s);
}
我有一个小Java问题,不知道有没有人能快速解答一下?
我正在遍历一个输入字符串,可能是一个名称,其中可能包含一个单引号。当它出现时,我希望能够在循环中使用它。这是一个例子。
String input_string = "some name with o'clock for example";
String[] delims = {" ", "O'", "L'", "D'"};
...
for (String s : delims) {
String[] split_words = input_string.split(delimiter);
for (String word : split_words) {
System.out.println("delimter is " + s);
System.out.println("word is "+ word);
}
}
输出为:
delimter is word is some
delimter is word is name
delimter is word is with
delimter is word is o'clock
delimter is word is for
delimter is word is example
delimter is 'O'' word is some name with o'clock for example
delimter is 'L'' word is some name with o'clock for example
delimter is 'D'' word is some name with o'clock for example
它与 space 配合使用时效果很好,但由于单引号的存在,事情在点钟阶段变得可疑。有什么想法吗?
String.split
区分大小写。它不会围绕您的 "o'"
拆分,因为您已要求它围绕 "O'"
拆分。它与单引号无关。
// This loop prints:
// some name with
// clock for example
for (String s: "some name with o'clock for example".split("o'")) {
System.out.println(s);
}