Hi all,
Firstly I am new to java so your help would be greatly appreciated.
I have been searching the net for a function that converts a string to Title Case. As of yet I have had no joy.
If anyone can help.
Thanks,
Dean.
Printable View
Hi all,
Firstly I am new to java so your help would be greatly appreciated.
I have been searching the net for a function that converts a string to Title Case. As of yet I have had no joy.
If anyone can help.
Thanks,
Dean.
Hi Dean,
Here you go,
Hope it helps.
Graham
//---------------------------------------------
public class StringUtils
{
static String toTitleCase(String stringToConvert)
{
// First thing to do is to create a string buffer as you
// cannot change a string
StringBuffer sb = new StringBuffer(stringToConvert);
// Go through the string, every time you come across
// a new word set the first letter to upper case
boolean haveSeenSpace = true; // Set it initially to true so that we set
// the first letter
for(int i = 0; i < sb.length();i++)
{
if(sb.charAt(i) == ' ')
{
haveSeenSpace = true;
}
else
{
// Must be a letter so check to see if the last item was
// a space to set to upper case
if(haveSeenSpace)
{
sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
haveSeenSpace = false;
}
else
{
// Must be a letter so push to lower
sb.setCharAt(i, Character.toLowerCase(sb.charAt(i)));
}
}
}
return (sb.toString());
}
/*
* Main routine to test with
*/
public static void main(String[] args)
{
System.out.println(StringUtils.toTitleCase("this is a string"));
System.out.println(StringUtils.toTitleCase("THIS IS A STRING"));
}
}
//-------------------------------------------