![](/img/trans.png)
[英]Java - how to split a string into a new line, after every punctuation mark?
[英]Java split a string by space, new line, tab, punctuation
大家。
我有这样的字符串
String message = "This is the new message or something like that, OK";
我想把它拆分成数组
String[] dic = {"this", "is", "the", "new", "message", "or", "something", "like", "that", "OK"};
我用了
message = message.split("\\s+");
问题在于它包含“那个”,而不是“我想要的”。 请教我如何解决它。 谢谢
你可以做
String[] dic = message.split("\\W+");
\\\\W
表示不是字母数字字符。
您可以使用StringTokenizer
String message = "This is the new message or something like that, OK";
String delim = " \n\r\t,.;"; //insert here all delimitators
StringTokenizer st = new StringTokenizer(message,delim);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
使用番石榴 :
// define splitter as a constant
private static final Splitter SPLITTER =
Splitter.on(CharMatcher.WHITESPACE.or(CharMatcher.is(','))
.trimResults()
.omitEmptyStrings();
// ...
// and now use it in your code
String[] str = Iterables.toArray(SPLITTER.split(yourString), String.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.