Link to home
Start Free TrialLog in
Avatar of humberss
humberss

asked on

Java string capitalize testing

Im inputting  a users name as 2 strings first name last name  and I want to test if the first letter of their first name and last name  is capitalize and only the first letter if not it needs to print an error message for the user to correct the problem.
Avatar of Mick Barry
Mick Barry
Flag of Australia image

You can use the split() method to break up first and last name

String[] names = input.split(" ");

you can use the Character class and the String charAt() method to check

char c first = names[0].charAt(0);
if (Character.isLowerCase(first))
{
   // first character is lower case


do the same for the 2nd name

Avatar of Weetbixiron
Weetbixiron

It sounds to me like you are storing their first and last name seperately, so it would be more like this:

if( Character.isLowerCase(firstName.charAt(0)) )
{
       //Print error
}
else
{
      if( Character.isLowerCase( lastName.charAt(0) )
     {
             //print error
     }
}
Some names have caps that aren't the first letter, but if you want to force it you could do the first bit of code.

If you just want to check use a Pattern and Match
        firstName = firstName.substring(0,1).toUpperCase() + firstName.substring(1).toLowerCase();
 
 
 
 
        Matcher m = Pattern.compile("^[A-Z]+[a-z]*$").matcher(firstName);
        if(m.matches())
        {
            System.out.println("valid");
        }
        else
        {
            System.out.println("invalid");
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of mohgupta
mohgupta

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial