Capitalize a String in Java

An example on making the characters after the space capital if they are not, in Java. Here is a logic that i've written and that's what i can do. Still more efficient logics are appreciated in the comments. Thanks and go ahead. The [main logic] will also work in any programming language.


Let's capitalize!



import java.util.*;
class CapitalizeString
{


public static void main(String args[])
{


// Create Scanner object for taking input from the user

Scanner s=new Scanner(System.in);


// Read a string from the user and store it in st

String st=s.nextLine();


// Convert string to char array

char[] c=st.toCharArray();


// Loop till end of the char array

for(int i=0;i<c.length;i++)
{


// If char at index i is a space, then..
if((c[i]==' '))
{


// If the character after space is a small alphabet i.e. ascii values of a-z are from 97-122

if((c[i+1]>=97)&&(c[i+1]<=122))
{


/*


At that position put capital of that alphabet,
ascii values of A-Z are 65-90, so for every
particular small and capital alphabet there is a difference of 32
Also typecast to char from int.


*/

c[i+1]=(char)(c[i+1]-32);


}


}


// Make even the first letter capital
else if(i==0)
{


// The same as above, but for the current char [first char]

if((c[i]>=97)&&(c[i]<=122))
{


c[i]=(char)(c[i]-32);


}


}


}


// Show it to the user

System.out.println("Capitalized: "+new String(c));


}


}

I think every thing is clear as every statement is explained above, so it will be useful for the future reference too. Go ahead with the output.

Output


gowtham gutha
Capitalized: Gowtham Gutha

Note: No problem if spaces occur, they do not change. If you have any try trimming the spaces by calling st.trim() here and then convert it to char[]. The code might look like this.

Change, char c[]=st.toCharArray(); to


char c[]=st.trim().toCharArray();


Posted by at on

Tags: String Handling,