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
Michael MMichael M 

Capitalization list back to string

Hello, I have a daily-scheduled-import of several new records, and names come in with inconsistent capitalization. I want my before insert trigger to make all the names appear normal (first letter of each name capital, the rest lower case.) I found code so far which does this but it leaves it as a list. How can this return a normal string of the name, with first then last name, in the normal format I want? 

String s;
     s = 'joHN JONSOn';
String [] lines = s.split('\n');
integer j = 0;
            for (String line:lines) {
String [] words = line.split(' ');
integer i = 0;
                for (String word:words) {
                    words[i] = word.trim().tolowercase().capitalize();
                    i++;
                }
                lines[j] = String.join(words,' ');
                j++;
                s = string.valueof(lines);
                system.debug(s);
            }


 
Best Answer chosen by Michael M
Prafull G.Prafull G.
Hello Michael,

Try following
String s;
s = 'joHN JONSOn';
String normalizedString = s.toLowerCase();

// Hold each word
List<String> listSubStrings = new List<String>();
// Split
for(String ss : normalizedString.split(' ')) {
	// Capitalize each piece
	ss = ss.capitalize();
	listSubStrings.add(ss);
}
// Join
String finalString =  String.join(listSubStrings, ' ');
System.debug(finalString);

Let me know if this helps.
 

All Answers

Prafull G.Prafull G.
Hello Michael,

Try following
String s;
s = 'joHN JONSOn';
String normalizedString = s.toLowerCase();

// Hold each word
List<String> listSubStrings = new List<String>();
// Split
for(String ss : normalizedString.split(' ')) {
	// Capitalize each piece
	ss = ss.capitalize();
	listSubStrings.add(ss);
}
// Join
String finalString =  String.join(listSubStrings, ' ');
System.debug(finalString);

Let me know if this helps.
 
This was selected as the best answer
Michael MMichael M
@Prafull, that worked, thank you!