1

I'm looking to split a sentence into an array of words separated by a comma in 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. Ideas? Thanks!

4

3 回答 3

6

The easiest way would be to use String#replaceAll(), replacing spaces with ,:

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.

于 2012-08-26T08:21:58.707 回答
3

对一个或多个空格使用正则表达式并将其替换为“,”,如下所示-

"The dog jumped".replaceAll("\\s+", ",")
于 2012-08-26T08:26:22.660 回答
-1

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. I won't give you the exact code,because this smells like an assignment :)

于 2012-08-26T08:22:59.240 回答