Write a function charCount() to count the characters code example
Example 1: count letters numbers and characters
public static String countLetter(String str){
String abc=str;
int a=0,b=0;
while(str.length()>0){
int i=0;
String ch=str.substring(i,i+1);
if(ch.matches(".*[a-zA-Z].*")){
a++;
}else if (ch.matches(".*[0-9].*")){
b++;
}
str=str.substring(i+1);
}
return abc + " has "+a+" letters "+b+" digit
and "+(abc.length()-(a+b))+" other characters ";
OR+++++++++++++++++++++++++++++++++
static void findSum(String str)
{
int total= str.length();
str = str.replaceAll("\\s", "");
int num =0;
int letter=0;
int i=0;
while(i "+num +
" numbers -> "+ (total-letter-num) + " other chars");
}
Example 2: count characters in string
# count characters iterative
def count_chars(s)
count = Hash.new(0)
s.split("").each do |x|
count[x] += 1
end
count
end
# count characters functional
s.chars.map {|c| [c, s.chars.count(c)] }.to_h