The String length() method return the total length of string but i need the count of characters
Example if the string is 'm*tt-', the # of characters will be 3 even though the length of string is 5
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityThe String length() method return the total length of string but i need the count of characters
Example if the string is 'm*tt-', the # of characters will be 3 even though the length of string is 5
String alphaChars = searchString.replaceAll('[^A-Za-z .]','');
Integer charLength = alphaChars.length();
Another mechanism that you could consider depending on the length of your source and the memory usage of the regex replace method, could be implemented like this using Set
collections and the .getChars()
method on the String
class.
String validCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
List<Integer> charsToInclude = validCharacters.getChars();
String sourceString = 'I love SFSE';
List<Integer> sourceChars = sourceString.getChars();
system.debug(sourceChars);
// create a unique collection of all characters and then retain only those we desire
Set<Integer> charSet = new Set<Integer>(sourceChars);
charSet.retainAll(charsToInclude);
// output unique characters
system.debug(charSet);
// count unique characters
system.debug(charSet.size());
debug output
// system.debug(sourceChars);
(73, 32, 108, 111, 118, 101, 32, 83, 70, 83, ...)
// system.debug(charSet);
{69, 70, 73, 83, 101, 108, 111, 118}
// system.debug(charSet.size());
8
You can try out this type of logic, it will work:
public Integer getCharLength(String input){
String validCharString = 'abcdefghijklmnopqrstuvwxyz';
Integer count = 0;
for (integer i=0;i<input.length();i++){
if(validCharString.contains((input.mid(i,1)).toLowerCase())) {
count++;
}
}
return count;
}
System.debug('count=' + getCharLength('m*tt-'));