【问题标题】:Force a stringBuilder to an upper case强制 stringBuilder 为大写
【发布时间】:2015-06-26 04:17:38
【问题描述】:

我想知道是否有任何类似 toUpperCase 之类的东西用于 StringBuilder?下面是我的代码,我试图接受用户输入的短语并将其转换为首字母缩略词。有人通过建议 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

【问题讨论】:

  • 答案取决于您何时要将其转换为大写...

标签: java stringbuilder toupper


【解决方案1】:

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

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

或在从 StringBuilder 获取字符串时将字符串转为大写:

System.out.println("The acronym of the three words you entered is: " + acronym.toString().toUpperCase());

【讨论】:

  • 太完美了!谢谢伊兰!我实际上尝试过,但我把 .toUpperCase 放在了错误的位置。感谢您的帮助,你们都摇滚!
【解决方案2】:

只需将大写字符串附加到 StringBuilder。

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

从 StringBuilder 获取字符串时或将字符串大写。

System.out.println("The acronym of the three words you entered is: " + acronym.toString().toUpperCase());

如果您需要库,请查看 Apache Common Lang WordUtilsWordUtils.capitalize(str)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2011-01-02
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多