Force a stringBuilder to an upper case

16.1k views Asked by At

I was wondering if there is anyway to use something like the toUpperCase for StringBuilder? Below is my code, I am trying to take user input of a phrase and turn it into an acronym. Someone helped me out by suggesting StringBuilder but I can't figure out if there is a way to make the acronym upper case. Any help is greatly 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
2

There are 2 answers

1
Eran On BEST ANSWER

Just append upper case Strings to it :

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

or turn the String to upper case when getting the String from the StringBuilder :

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

Just append 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 upper case the String when getting it from StringBuilder.

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

If you need a library take a look at Apache Common Lang WordUtils, WordUtils.capitalize(str).