Converting a sentence string to a string array of

2019-01-13 05:48发布

I need my Java program to take a string like:

"This is a sample sentence."

and turn it into a string array like:

{"this","is","a","sample","sentence"}

No periods, or punctuation (preferably). By the way, the string input is always one sentence.

Is there an easy way to do this that I'm not seeing? Or do we really have to search for spaces a lot and create new strings from the areas between the spaces (which are words)?

14条回答
虎瘦雄心在
2楼-- · 2019-01-13 06:29

Try using the following:

String str = "This is a simple sentence";
String[] strgs = str.split(" ");

That will create a substring at each index of the array of strings using the space as a split point.

查看更多
Viruses.
3楼-- · 2019-01-13 06:31

The easiest and best answer I can think of is to use the following method defined on the java string -

String[] split(String regex)

And just do "This is a sample sentence".split(" "). Because it takes a regex, you can do more complicated splits as well, which can include removing unwanted punctuation and other such characters.

查看更多
登录 后发表回答