count 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<str.length()){
char ch = str.charAt(i);
if (Character.isDigit(ch))
num ++;
else {
letter++;
}
i++;
}
System.out.println(letter + " letters -> "+num +
" numbers -> "+ (total-letter-num) + " other chars");
}
Example 2: how to count words in string
String str = "I am happy and why not
and why are you not happy and you should be";
String [] arr = str.split(" ");
Map<String, Integer> map = new HashMap<>();
for (int i=0 ; i < arr.length ; i++){
if (!map.containsKey(arr[i])){
map.put(arr[i],1);
} else{
map.put(arr[i],map.get(arr[i])+1);
}
}
for(Map.Entry<String, Integer> each : map.entrySet()){
System.out.println(each.getKey()+" occures " + each.getValue() + " times");
}
Example 3: counting special characters
int count = str.length() - str.replaceAll("\\$","").length();
Example 4: charcount
public static int charCount(String userInput) {
char[] StringArray = userInput.toCharArray();
HashMap<Character, Integer>charCount = new HashMap<Character, Integer>();