HOW TO SET FIRST LETTER FROM STRING FOR CAPITALIZATION IN JAVA?

Pawan Shukla

Total Post:29

Points:203
Posted by  Pawan Shukla
 1764  View(s)
Ratings:
Rate this:

I want to take a String input form a user, and format it so that the first letter is capitalized and the rest is not. I would like to do this by splitting the first letter from the string and use .toUpperCase() on it and use .toLowerCase() on the rest, and then merge them back together.

I have an idea, but can't solve everything:

userInput = input.nextLine();

String firstLetter = ???

firstLetter.toUpperCase();

restOfString.toLowerCase();

String merged = firstLetter + restOfString;

This does NOT seem to work:

            name = input.nextLine();

            firstLetter = name.substring(0,1);

            remainingString = name.substring(1);

            firstLetter.toUpperCase();

            remainingString.toLowerCase();

            name = firstLetter + remainingString;

  1. Hugh Jackman

    Post:52

    Points:366
    Re: How to set First letter from String for capitalization in java?

    You can use substring.

    String firstLetter = userInput.substring(0,1); //takes first letter

    String restOfString = userInput.substring(1); //takes rest of sentence

    firstLetter = firstLetter.toUpperCase(); //make sure to set the string, the methods return strings, they don't change the string itself

    restOfString = restOfString.toLowerCase();

    String merged = firstletter + restOfString;

     

     If you wish to do error-checking on the user's input:

    if(userInput.length < 2) {

        throw new InputMismatchException("Sentence to short to properly capitalize!";

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!