简体   繁体   中英

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?

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. It's not splitting around your "o'" because you've asked it to split around "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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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