简体   繁体   English

Java-用逗号分割字符串数组

[英]Java - Splitting String Array with a Comma

I'm looking to split a sentence into an array of words separated by a comma in Java. 我希望将一个句子拆分成单词数组,并用Java中的逗号分隔。

That is, I want a sentence like: 也就是说,我想要一个这样的句子:

"The dog jumped" “狗跳了”

"high over the" “高过”

to become 成为

"The,dog,jumped" “那只狗跳了起来”

"high,over,the" “高处,上方”

I can't seem to get it to pick up the space and insert with a comma using the .split(",") method but that doesn't appear to work, the result is still the original. 我似乎无法使用.split(“,”)方法来获取空间并用逗号插入,但这似乎不起作用,结果仍然是原始的。 Ideas? 有想法吗? Thanks! 谢谢!

The easiest way would be to use String#replaceAll() , replacing spaces with , : 最简单的方法是使用String#replaceAll()以替代空间,

String s = "The dog jumped";
String sWithComma = s.replaceAll(" ", ",");

If you want to allow for cases more complicated than the sample you posted (multiple spaces, tabs etc.), you should use this other answer . 如果您想让情况比所发布的示例复杂(多个空格,制表符等),则应使用其他答案

将正则表达式用于一个或多个空间,然后将其替换为“,”,如下所示:

"The dog jumped".replaceAll("\\s+", ",")

Many ways to do this. 有很多方法可以做到这一点。 I would look at using strtok for a task like this, or maybe the apache commons StringUtils package, or replaceAll. 我会考虑将strtok用于此类任务,或者使用apache commons StringUtils软件包或replaceAll。 I won't give you the exact code,because this smells like an assignment :) 我不会给您确切的代码,因为这闻起来像是作业:)

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

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