Force stringBuilder to uppercase

I was wondering if there is a way to use something like toUpperCase for the StringBuilder? Below is my code, I am trying to take user input of a phrase and turn it into an acronym. Someone helped me by suggesting StringBuilder, but I can't figure out if there is a way to make the upper case abbreviation. Any help is appreciated.

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

      

+3


source to share


2 answers


Just add lowercase lines to it:

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

      



or convert the string to uppercase when getting the string from StringBuilder:

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

      

+6


source


Just add an upper case string to 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 

      

Or an uppercase String when retrieved from a StringBuilder.



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

      

If you need a library, see the Common Lang the Apache WordUtils , WordUtils.capitalize(str)

.

0


source







All Articles