Yesterday, I published the Use Flow To Output First Letter of Every Word showing how one could use native Flow to fetch the first letter in every word. Today, I wanted to do that in Apex so one can compare and contrast the two.
Get First Letters of Every Word Flow Equivalent Apex
public static String getFirstLettersOfWords(String input) {
String firstLetters = '';
String inputCopy = input;
String currentLetter = '';
String lastLetter = '';
// If no string, return empty string.
if (String.isBlank(inputCopy)) {
return firstLetters;
}
while(String.isNotBlank(inputCopy)) {
currentLetter = inputCopy.left(1);
// isBlank returns true if the string is all whitespace too
// so that's why the first condition for lastLetter works.
if (String.isBlank(lastLetter) &&
String.isNotBlank(currentLetter) &&
currentLetter.isWhitespace() == false) {
firstLetters += currentLetter;
}
lastLetter = currentLetter;
// If more than one character, pop off the first character
// and set the input to the remainder. Otherwise, set
// the input to an empty string since there's nothing left so
// the loop will end.
if (inputCopy.length() > 1) {
inputCopy = inputCopy.right(inputCopy.length() - 1);
}
else {
inputCopy = '';
}
}
return firstLetters;
}
This is not the prettiest code since it’s inlined but it works! Being able to use the Apex string methods greatly simplifies the logic. I really wanted to be able to just iterate over the characters in the string using the for each to simplify this further but Apex doesn’t allow that! The next example shows how I was able to iterate over the characters one-by-one without continuously shifting the string by 1 using the right function.
Get First Letters of Every Word By Iterating Characters Apex
public static String getFirstLettersOfWords2(String input) {
String firstLetters = '';
String lastLetter = '';
// If no string, return empty string.
if (String.isBlank(input)) {
return firstLetters;
}
Integer inputLength = input.length();
for (Integer charIndex = 0; charIndex < inputLength; ++charIndex) {
// One can't get a particular character string at an index.
// However, one can get the character code and then convert it back
// to a string.
Integer characterCode = input.charAt(charIndex);
String currentCharacter = String.fromCharArray(new Integer[]{ characterCode });
// isBlank returns true if the string is all whitespace too
// so that's why the first condition for lastLetter works.
if (String.isBlank(lastLetter) &&
String.isNotBlank(currentCharacter) &&
currentCharacter.isWhitespace() == false) {
firstLetters += currentCharacter;
}
lastLetter = currentCharacter;
}
return firstLetters;
}
This is a little cleaner without the “shifting logic” and it seems to run faster too.