简体   繁体   English

当分隔符具有单引号时,Java String split()函数无法按预期工作

[英]Java String split() function not working as expected when delimiter has single quote

I have a small Java problem, and I don't know if anyone has a quick answer? 我有一个小的Java问题,我不知道是否有人有快速的答案?

I'm looping over an input string, possibly a name, which may contain a single quote. 我循环一个输入字符串,可能是一个名字,可能包含一个引号。 When it does, I'd like to be able to work with it during the loop. 当它发生时,我希望能够在循环中使用它。 Here's an example. 这是一个例子。

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);
  }
}

The output is: 输出是:

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

It works fine with a space, but because of the single quote, things get fishy at the o'clock stage. 它在空间上工作得很好,但由于单引号,事情在下午阶段变得可疑。 Any ideas? 有任何想法吗?

String.split is case-sensitive. String.split区分大小写。 It's not splitting around your "o'" because you've asked it to split around "O'" . 它并没有在你的"o'"周围分裂,因为你已经要求它分开"O'" It has nothing to do with the single quote. 它与单引号无关。

// 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM