2

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

2
  • which are the characters you want to count? A to Z and 0 to 9? – Santanu Boral Jul 8 '16 at 20:46
  • i want to count A to Z – snehakem Jul 8 '16 at 20:48
4
String alphaChars = searchString.replaceAll('[^A-Za-z .]','');

Integer charLength = alphaChars.length();
2

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
0

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-')); 
1
  • i have got an easier solution. Thanks for the help – snehakem Jul 8 '16 at 21:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.