function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
nagennagen 

Convert To Title Case

Hi,
Is there any way to convert String /Sentence to Title Case in Apex.

Convert From
"this is a sentence"
To
"This Is A Sentence"


Thanks
R


mikefmikef
nagen:

String.proper() doesn't exisit in Apex, and I think that is what you want.
Excel work sheets have this function.

You will have to write this method yourself.


Message Edited by mikef on 04-08-2008 03:05 PM
philbophilbo
Here's one way to do it:

String toTitleCase ( String inStr ) {

    String outStr = '';
    for ( String word : inStr.trim ().split ( ' +' ) ) {
        outStr += ( outStr == '' — '' : ' ' )
               + word.subString ( 0 , 1 ).toUpperCase ()
               + ( word.length () > 1 – word.SubString ( 1 ) : '' );

    return outStr;
}

Challenge:  can anybody out there make this more efficient?

-philbo

ministe2003ministe2003

I wrote a method that looks like this:

 

 

//converts a given string to Title Case where the
//first letter of every word is capitalised and the rest are small
public String toTitleCase(String phrase){
  String titlePhrase = '';
  //a set of words that should always (or at least, almost always) be in lower case when in Title Case
  //eg The Day of the Jackal.  First and last word of a phrase should always be Capped though.
  Set<String> forceLower = new Set<String>{'of', 'the', 'for', 'and', 'a', 'to', 'at' ,'an', 'but', 'if', 'or', 'nor'};

  if(phrase != null && phrase.length() > 0){
    String[] splitPhrase = phrase.trim().split(' ');
			
    for(integer i = 0; i < splitPhrase.size(); i++){
      if(!forceLower.contains(splitPhrase[i].toLowerCase()) || i == 0 || i == (splitPhrase.size()-1) ){
        titlePhrase += (splitPhrase[i].substring(0,1).toUpperCase())+(splitPhrase[i].substring(1).toLowerCase())+' ';
      }else{
        titlePhrase += splitPhrase[i].toLowerCase()+' ';
      }
    }
  }
    return titlePhrase.trim();
  }

 

 

Which is pretty good, it always capitalises the first and last words, other than that it capitalises everything that isn't in the list of conjunctions, which obviously you could customise.  If you wanted to avoid having to update code each time you thought of a new word you could make a picklist of values and pull them out with a describe call, meaning an administrator can add words to force to lower case as necessary.

 

I return a trim because I always add a space at the end of titlePhrase in preparation for the next word.

KenSFKenSF

Greetings: I am looking to convert names to all Uppercase for several objects because of names such as McMillan or McDonald. What would be efficient code to accomplish this.  Thanks

Kenn K.Kenn K.

Thanks for this, it looks good. I want to this in such a way that every time we do an insert or an update, this method runs. Do you know of a way I can incorporate this in a trigger? Maybe a sample trigger?

 

Thanks,

-K

DaveedDaveed
Short and sweet

public static String toProperCase(String value) {
        // Normalize - Convert to lowercase
        value = value.toLowerCase();

        // Hold each word
        List<String> pieces = new List<String>();

        // Split
        for(String s : value.split(' ')) {
            // Capitalize each piece
            s = s.capitalize();

            // Add to pieces
            pieces.add(s);
        }

        // Join
        return String.join(pieces, ' ');
    }
Patrick KarkabiPatrick Karkabi
Thanks Daveed, works great
Mike Gilbert 8Mike Gilbert 8
Here's a version that preserves whitespace.
private static Pattern wordPattern = Pattern.compile('\\w+');

public static String toTitleCase(String s) {
    if (s == null) {
        return null;
    }

    String result = '';
    Integer i = 0;
    Matcher m = wordPattern.matcher(s);

    while (m.find()) {
        result += s.substring(i, m.start());
        result += m.group().toLowerCase().capitalize();
        i = m.end();
    }

    result += s.substring(i, s.length());

    return result;
}
Sarthak Pani 29Sarthak Pani 29
@ministe2003 your code was really helpful. Saved me from a tiring session of pseudo-coding! :)
 
//converts a given string to Title Case where the
//first letter of every word is capitalised and the rest are small
public String toTitleCase(String phrase){
  String titlePhrase = '';
  //a set of words that should always (or at least, almost always) be in lower case when in Title Case
  //eg The Day of the Jackal.  First and last word of a phrase should always be Capped though.
  Set<String> forceLower = new Set<String>{'of', 'the', 'for', 'and', 'a', 'to', 'at' ,'an', 'but', 'if', 'or', 'nor'};

  if(phrase != null && phrase.length() > 0){
    String[] splitPhrase = phrase.trim().split(' ');
            
    for(integer i = 0; i < splitPhrase.size(); i++){
      if(!forceLower.contains(splitPhrase[i].toLowerCase()) || i == 0 || i == (splitPhrase.size()-1) ){
        titlePhrase += (splitPhrase[i].substring(0,1).toUpperCase())+(splitPhrase[i].substring(1).toLowerCase())+' ';
      }else{
        titlePhrase += splitPhrase[i].toLowerCase()+' ';
      }
    }
  }
    return titlePhrase.trim();
  }

 
Emily WillsonEmily Willson
Hey! This is pretty neat. But Why you have to write it on your own? I'm using this (https://essaytoolbox.com/case-converter) case convertor!
Shankar Kumar 47Shankar Kumar 47
Which is pretty good, it always capitalises the first and last words, other than that it capitalises everything that isn't in the list of conjunctions, which obviously you could customise. https://www.laweekly.com/masszymes-reviews/