Link to home
Start Free TrialLog in
Avatar of huzefaq
huzefaq

asked on

how to capitalize first letter and put space between a string

Hi

I get the state names from a link in this format

alabama
northCarolina etc

I capitalize the first letter using this code

String capitalize_chapterName = chapter_name.length()>1? chapter_name.substring(0,1).toUpperCase() + chapter_name.substring(1).toLowerCase() : chapter_name.toUpperCase();
it works fine for one word sattes
for northCarolina i need it to be North Carolina

Any help will be greatly appreciated
Avatar of kawas
kawas
Flag of United States of America image

you can capitalize the first letter using the method that you stated, for other letters, you could use the method isUpper in java.lang.Character.
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Character.html


create a string buffer and then loop through the string, character by character, and if the letter is uppercase, then add a space and the letter to the buffer, otherwise just add the letter.

using the character class, you can even perform more fine tunning like removing whitespaces, determining if the character is a letter or a digit, etc.
Avatar of Mick Barry
try:

s = s.replaceAll("([A-Z])", " {1}");
ASKER CERTIFIED SOLUTION
Avatar of slyong
slyong

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
Avatar of kaliyugkaarjun
kaliyugkaarjun

I havn't compiled...chk if it works for u

str="northCarolina"
StringBuffer  = new (str);
if (Character.isLowerCase(strbuf.charAt( 0)))
{
     Character.toUpperCase(strbuf.charAt( 0))
}

for ( i = 0;  i < strbuf.length();  i++ )
 {        
 
        ch = strbuf.charAt( i );
        if (Character.isUpperCase(ch))
        {
             strbuf.insert(i , " ");
        }
 }
 str=strbuf.toString();
 System.out.println(strbuf);