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!
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 .
将正则表达式用于一个或多个空间,然后将其替换为“,”,如下所示:
"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. I won't give you the exact code,because this smells like an assignment :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.