gpt4 book ai didi

java - 如何将每个句子的第一个字母转换为大写并将所有其他字母转换为小写?

转载 作者:行者123 更新时间:2023-11-29 05:32:27 25 4
gpt4 key购买 nike

我项目中的部分语法检查。我有一个段落,我想将每个句子的所有第一个字母都改为大写。句子中的所有其他字母必须小写。

"lijo was very intelligent.but his Character was not Good.He Played FootBall .
he is veryClever,and wise."

output

"Lijo was very intelligent.But his character was not good.He played football .
He is veryclever,and wise."

我是这样做的:

public static void main(String[] args) {
String org= "lijo was very 'intelligent . but his Character was not Good.He Played FootBall .he is veryClever,and wise.";
String [] temp=org.split("\\.");
int len=temp.length;
String ne = ".";
for(int i=0;i<len;i++)
{
temp[i]=temp[i].toUpperCase();
temp[i]=(temp[i].substring(0, 1)).toUpperCase()+(temp[i].substring(1, temp[i].length())).toLowerCase();
System.out.println(temp[i]);
}
}

有没有更简单的方法来做到这一点?

最佳答案

你可以这样做:

private static final Pattern SENTENCE_START = Pattern.compile("(?:^|[.]\\s*)([a-z])");
private String sentenceCase(String org) {
char[] chars = org.toCharArray();
Matcher m = SENTENCE_START.matcher(org);
while (m.find()) {
chars[m.start(1)] = Character.toUpperCase(chars[m.start(1)]);
}
return new String(chars);
}

正则解释:

(?:^|[.]\s*)([a-z])

Regular expression visualization

(?: ) - 未命名组
^ - 字符串的开始
| - 或
[.] - . 字符
\s* - 零个或多个空格
[a-z] - 小写字符

关于java - 如何将每个句子的第一个字母转换为大写并将所有其他字母转换为小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20658069/

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