java - 如何使用java将每个句子中句号后的首字母大写?

标签 java string

我目前正在学习如何操作字符串,我认为我需要一段时间才能习惯。我想知道如何在每个句子的句点后将字母大写。

输出是这样的:

输入句子:我很高兴。这是天才。

大写:我很高兴。这是天才。

我已经尝试创建自己的代码但它不起作用,请随时更正和更改它。这是我的代码:

package Test;

import java.util.Scanner;

public class TestMain {
    public static void main(String[]args) {
        String sentence = getSentence();
        int position = sentence.indexOf(".");

        while (position != -1) {
            position = sentence.indexOf(".", position + 1);
            sentence = Character.toUpperCase(sentence.charAt(position)) + sentence.substring(position + 1);
            System.out.println("Capitalized: " + sentence);
        }

    }

    public static String getSentence() {
        Scanner hold = new Scanner(System.in);
        String sent;
        System.out.print("Enter sentences:");
        sent = hold.nextLine();
        return sent;
    }
}

棘手的部分是我如何将句点 (".") 后的字母大写?我没有很多字符串操作知识,所以我真的被困在这个领域。

最佳答案

试试这个:

package Test;
import java.util.Scanner;

public class TestMain {
    public static void main(String[]args){

        String sentence = getSentence();
        StringBuilder result = new StringBuilder(sentence.length());
        //First one is capital!
        boolean capitalize = true;

        //Go through all the characters in the sentence.
        for(int i = 0; i < sentence.length(); i++) {
            //Get current char
            char c = sentence.charAt(i);

            //If it's period then set next one to capital
            if(c == '.') {
                capitalize = true;
            }
            //If it's alphabetic character...
            else if(capitalize && Character.isAlphabetic(c)) {
                //...we turn it to uppercase
                c = Character.toUpperCase(c);
                //Don't capitalize next characters
                capitalize = false;
            }

            //Accumulate in result
            result.append(c);
        }
        System.out.println(result);
    }

    public static String getSentence(){
        Scanner hold = new Scanner(System.in);
        String sent;
        System.out.print("Enter sentences:");
        sent = hold.nextLine();
        return sent;
    }
}

这是做什么的,它按顺序推进字符串中的所有字符,并保持下一个字符需要大写的状态。

enter image description here

按照评论进行更深入的解释。

关于java - 如何使用java将每个句子中句号后的首字母大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32249723/

相关文章:

Java 添加到列表 NullPointerException

string - 查找字符串中子字符串的索引,指定起始索引

JAVA 替换除可变字符串以外的所有内容

java - 解析字符串 "((1/2)/3/)4"和其他类似字符串的好方法

java - 了解测试套件

java - 如何在 ActionListener 中添加 Swing 组件?

java - 由于没有窗口焦点,返回主 Activity 会导致 Dropping 事件

java - 这个函数每次被调用时都会创建一个新的字符串吗?

C++ 从 const char 到 string 的自动隐式转换

java - java Stream.peek() 如何影响字节码?