将句子字符串转换为Java中的字符串数组 [英] Converting a sentence string to a string array of words in Java

查看:170
本文介绍了将句子字符串转换为Java中的字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的Java程序采用如下字符串:

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

推荐答案

字符串。 split()将完成你想要的大部分工作。然后,您可能需要循环显示单词以取出任何标点符号。

String.split() will do most of what you want. You may then need to loop over the words to pull out any punctuation.

例如:

String s = "This is a sample sentence.";
String[] words = s.split("\\s+");
for (int i = 0; i < words.length; i++) {
    // You may want to check for a non-word character before blindly
    // performing a replacement
    // It may also be necessary to adjust the character class
    words[i] = words[i].replaceAll("[^\\w]", "");
}

这篇关于将句子字符串转换为Java中的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆