【问题标题】:How to split string into words in java preserving punctuation?java - 如何在保留标点符号的Java中将字符串拆分为单词?
【发布时间】:2018-02-11 00:52:10
【问题描述】:

这是输入

hello; this is cool?
great,   awesome

我希望我的输出是

hello;
this
is
cool?
great,
awesome

我基本上认为一个词中有标点符号。这就是我对我的应用程序的词的定义。我想根据空格、制表符和换行符拆分单词。大多数stackoverflow问题和答案都假设单词不包含标点符号,那么我将如何解决这个问题?

【问题讨论】:

标签: java regex string split words


【解决方案1】:

直接在代码中注释和解释:

//1st possibility: every single whitespace character (space, tab, newline, carriage return, vertical tab) will be treated as a separator
String s="hello; this is cool?\ngreat,   awesome";
String[] array1 = s.split("\\s");
System.out.println("======first case=====");
for(int i=0; i<array1.length; i++)
    System.out.println(array1[i]);

//2nd possibility (groups of consecutive whitespace characters (space, tab, newline, carriage return, vertical tab) will be treated as a single separator
String[] array2 = s.split("\\s+");
System.out.println("=====second case=====");
for(int i=0; i<array2.length; i++)
    System.out.println(array2[i]);
//notice the difference in the output!!!

输出:

======first case=====
hello;
this
is
cool?
great,
         <----- Notice the empty string
         <----- Notice the empty string
awesome
=====second case=====
hello;
this
is
cool?
great,
awesome

【讨论】:

  • 如果您投反对票,能否发表评论?为了让我们得到反馈!谢谢
猜你喜欢
  • 2010-09-26
  • 1970-01-01
  • 2020-01-11
  • 2012-11-16
  • 2014-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多