gpt4 book ai didi

java - 获取每个单词都以大写字符开头的短语

转载 作者:行者123 更新时间:2023-11-30 08:28:44 25 4
gpt4 key购买 nike

目前,我尝试使用 Character.isUpperCase 在句子中获取以大写字母开头的单词。但是现在我只想检索句子中的短语,其中短语的每个单词中的第一个字母都是大写的。我应该怎么做。

例如“这是一个例句,因此 Ang Mo Kio Avenue 1 是 Ang Mo Kio 的一部分。”

我会检索“Ang Mo Kio Avenue 1”和“Ang Mo Kio”。

String s = "This is a sample sentence so that Ang Mo Kio Avenue 1 is part of Ang Mo Kio.";
String[] words = s.split("[^a-zA-Z']+");
for (int i = 0; i < words.length; i++) {
if (Character.isUpperCase(words[i].charAt(0))) {
System.out.println(words[i]);
}}

真正的目的是提取3个或更多的大写单词,可选地后跟一个数字

最佳答案

i would like to only retrieve phrases in a sentence where all the 1st letter in every word of the phrase is upper case

为此,您需要捕获连续的大写单词,并将它们附加到 StringBuilder 中。如果出现小写字母则初始化 StringBuilder。

尝试,

StringBuilder answer = new StringBuilder();
String s
= "This is a sample sentence so that Ang Mo Kio Avenue 1 is part of Ang Mo Kio.";
String[] words = s.split("\\s+");
int count=0;
for (int i = 0; i < words.length; i++) {
char firstChar=words[i].charAt(0);
if (Character.isUpperCase(firstChar)
||(count>0 && Character.isDigit(firstChar))) {
answer.append(" "+words[i]);
count++;
} else {
//To avoid less than 3 word apply this logic.
if(count>2){
System.out.println(answer);
}
count=0;
answer = new StringBuilder();
}
}
System.out.println(answer);// Also need to print answer here.

输出:

 Ang Mo Kio Avenue 1
Ang Mo Kio.

关于java - 获取每个单词都以大写字符开头的短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20046581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com