Convert a string to "Title Case"???


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Convert a string to "Title Case"???

Hybrid View

  1. #1
    Join Date
    May 2004
    Posts
    1

    Unhappy 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.

  2. #2
    Join Date
    May 2004
    Location
    Durham, UK
    Posts
    174
    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
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center