【问题标题】:How do I separate Strings with an apostrophe in them in Java?如何在 Java 中用撇号分隔字符串?
【发布时间】:2020-04-24 23:14:01
【问题描述】:

我试图将“因此美丽的玫瑰可能永远不会死”这一行分成单独的单词,并且我的代码有效 - 除了撇号。 "beauty's" 仍然返回为 "beauty's" 而不是 "beauty" 和 "s"。

这就是我正在尝试的:

String line = "That thereby beauty’s rose might never die,";
String[] words = line.split("[' ,]");

我不太了解在 Java 中添加多个分隔符,但这似乎适用于除撇号之外的所有内容。有人可以帮助我并告诉我我能做些什么来解决这个问题吗?

【问题讨论】:

    标签: java string split delimiter


    【解决方案1】:

    仔细查看line 的撇号和拆分撇号。他们是不同的角色。 != '。您很可能希望将第一个转换为第二个。

    一些代码供你思考:

    String line = "That thereby beauty’s rose might never die,";
    String[] words = line.split("[' ,]");
    System.out.println(Arrays.toString(words));
    
    line = "That thereby beauty's rose might never die,";
    words = line.split("[' ,]");
    System.out.println(Arrays.toString(words));
    

    输出:

    [That, thereby, beauty’s, rose, might, never, die]
    [That, thereby, beauty, s, rose, might, never, die]
    

    【讨论】:

    • 非常感谢!这真的很有帮助 - 不敢相信我犯了这样一个菜鸟错误
    • @user11610667 请考虑将此答案标记为已接受,以便我获得声誉!
    【解决方案2】:

    ' 替换为

    String[] words = line.split("[’ ,]");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 2017-10-04
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多