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!

1
  • 1
    simply googling would've solved this Commented Aug 26, 2012 at 8:29

3 Answers 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.

Sign up to request clarification or add additional context in comments.

2 Comments

I would advise using "\\s+" instead of " " to catch tabs and multiple spaces as well.
@amit Fair point - I assumed from the question that the input would be always well formed. Have added link to the other answer.
3

Using regex for one or more space and replacing it with "," like this-

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

Comments

-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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.