Making First Character of Every Word in Upper Case and Others in Lower Case in a Java String

Here I am giving a code in java to make first character in upper case and rest in lower case

class UpperFirst
{
static String[] breakAtSpace(String s)
{
int arrayIndex=0;
int first=0;
int last=0;

String arr[]=new String[10];

while(last<s.length())
{
last=s.indexOf(” “,first);
if(last==-1) last=s.length();
arr[arrayIndex]=s.substring(first,last);
first=last+1;
arrayIndex++;
}
return arr;
}

public static void main(String arg[])
{
String s= “here is MY STRING in DiffeRent cAse LetterS”;
String arr[]= UpperFirst.breakAtSpace(s);
StringBuffer result=new StringBuffer(“”);

for(int i=0;i<arr.length;i++)
{
if(arr[i]!=null)
{
String str=arr[i];
for(int j=0;j<str.length();j++)
{
if(j==0) result.append(str.substring(j,j+1).toUpperCase()) ;
else result .append( str.substring(j,j+1).toLowerCase());
}
result.append(” “);
}
}
System.out.print(result);

}

}

The logic I have used is that I have broken the string into words by searching space(” “) character in string. Then stored every word in an array. This is implemented in breakAtSpace() method.
In main method, by checking (j==0), I have changed the first character of every word in upper case and rest in lower case.
the line result.append(" "); appends an space after every word.

The output is:

Here Is My String In Different Case Letters

Advertisements

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: