我想知道是否有针对StringBuilder使用toUpperCase之类的东西?下面是我的代码,我试图让用户输入一个短语并将其转换为首字母缩写词。有人通过建议StringBuilder来帮助我,但是我不知道是否有办法使首字母大写。任何帮助是极大的赞赏。

public class ThreeLetterAcronym {

public static void main(String[] args) {
    String threeWords;
    int count = 0;
    int MAX = 3;
    char c;
    //create stringbuilder
    StringBuilder acronym = new StringBuilder();

    Scanner scan = new Scanner(System.in);

    //get user input for phrase
    System.out.println("Enter your three words: ");
    threeWords = scan.nextLine();

    //create an array to split phrase into seperate words.
    String[] threeWordsArray = threeWords.split(" ");

    //loop through user input and grab first char of each word.
    for(String word : threeWordsArray) {
        if(count < MAX) {
            acronym.append(word.substring(0, 1));
            ++count;

        }//end if
    }//end for

    System.out.println("The acronym of the three words you entered is: " + acronym);
    }//end main
}//end class

最佳答案

只需将大写字符串附加到它:

acronym.append(word.substring(0, 1).toUpperCase())

或从StringBuilder获取字符串时将字符串大写:
System.out.println("The acronym of the three words you entered is: " + acronym.toString().toUpperCase());

08-19 13:38