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

标签 java string

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

"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/

相关文章:

java - 使用 iText 创建 PDF 而不将其保存到临时文件

java - 为什么我正在创建的文本文件中缺少最后几行?

java - UDP Java 数据报

Java 程序输出应该是 true ,但它返回 false 为什么?

python - 使用python sqlite3模块,如何处理包含双引号的字段?

php - 修剪空白

java - 在Java中,我可以扫描字符串并将其存储为小写/大写字符,无论输入如何

java - 两个 JTextEdit 上的 GroupLayout.linkSize() 使它们的大小为零

c++ - std::wstring 不适用于 std::map<const wchar_t*, const char*> 的 [] 运算符

java - 编译时和运行时变量的绑定(bind)