replaceBadDigitsKeepCasing function
Replaces zeros with the letter 'O' in words that are mostly letters.
This function examines word strings and replaces any '0' characters
with 'O' (uppercase) or 'o' (lowercase) based on the casing of surrounding characters.
It only makes this replacement if the word is primarily composed of letters rather than digits.
word is the potentially corrected word.
Returns the word with zeros replaced by appropriate letter 'O' if applicable.
Implementation
String replaceBadDigitsKeepCasing(final String word) {
// If no zeros in the string, return as is
if (!word.contains('0')) {
return word;
}
// Count uppercase and lowercase letters to determine dominant case
int uppercaseCount = 0;
int lowercaseCount = 0;
for (final String char in word.split('')) {
if (isLetter(char)) {
if (isUpperCase(char)) {
uppercaseCount++;
} else {
lowercaseCount++;
}
}
}
// Determine which case to use for 'O' replacement
final String replacement = (uppercaseCount > lowercaseCount) ? 'O' : 'o';
// Replace all zeros with the appropriate case of 'O'
return word.replaceAll('0', replacement);
}