-
Convert a string to "Title Case"???
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"));
}
}
//-------------------------------------------
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks