Hello friends, In this post you will see a code sample that helps you to convert an string in title case/proper case in apex. Salesforce string class does not contains any method that helps you to do this but by using this code you can easily convert string in title case. So let's get started,

Convert an string in title/proper case in apex

You can use below code snippet to convert any string in title/proper case.

Code Snippet:

 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
Set<String> forceLower = new Set<String>{'is', '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();
}
Example:
 String sText='sALesForce Is a CRM';
system.debug(toTitleCase(sText));

Output:


Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.