我想在Java中将字符串分成每3个单词一组的部分。
例如:
“我想和我的父亲在公园散步”
我想要一个字符串:“我想要”,另一个字符串:“走在”。
我该如何做到这一点?
例如:
“我想和我的父亲在公园散步”
我想要一个字符串:“我想要”,另一个字符串:“走在”。
我该如何做到这一点?
以下是使用正则表达式的解决方案
String sentence = "I want to walk in the park with my father";
Pattern pattern = Pattern.compile("\\w+ \\w+ \\w+ ");
Matcher matcher = pattern.matcher(sentence);
while (matcher.find()) {
System.out.println(matcher.group());
}
String sentence = "I want to walk in the park with my father";
String[] words = sentence.split(" ");
List<String> threeWords = new ArrayList<>();
int length = words.length;
for (int ind = 2; ind < length; ind += 3) {
threeWords.add(words[ind - 2] + " " + words[ind - 1] + " " + words[ind]);
}
if (length % 3 == 1) {
threeWords.add(words[length - 1]);
} else if (length % 3 == 2) {
threeWords.add(words[length - 2] + " " + words[length - 1]);
}
words
),每次删除3个单词,将它们连接成一个字符串,并将其添加到我的最终ArrayList中就可以了。虽然这可能不是非常高效的性能,但它可以完成工作,而且很容易理解。// finalWords is your result
ArrayList<String> finalWords = new ArrayList<String>();
ArrayList<String> words = new ArrayList<String>();
for(String str : "I want to walk in the park with my father".split(" "))
words.add(str);
while(words.size() > 0)
{
String str = "";
for(int i = 0; i < 3; i++)
{
if(words.size() > 0)
{
str += words.get(0) + " ";
words.remove(0);
}
}
finalWords.add(str);
}
编辑:由于你写了这句话:
我知道如何将它分成单个单词,但不知道如何分组。
在评论中,将它分成单词组很简单。首先,将你的句子分成单词,然后将这些单词连接成新字符串,每三个为一组,并将连接后的字符串添加到你选择的列表/数组中。
Person person = new Person(/*ID HERE*/);
的整个想法基本上是虚假的。因为它要求你的“客户端”代码知道要使用的ID。而这是不应该的。new()
应该自动计算ID,并分配一个唯一值,而无需“客户端”进行任何操作。 - GhostCat