topic:
Given a string str = "yekmaakkccekymbvb". Count the number of characters in the string and print out the number of each character.
Ideas:
Replace the first character of the string with [""], and then calculate the difference with the string before substitution, and the difference obtained is the number of the first character.
Code:
public class CharTypeStat{ public static void main(String[] args){ String str = "yekmaakkccekymbvb"; int i = 0;//Count the number of characters while(!"".equals(str)){ String s = str.substring(0, 1);//Get the number of characters to be counted String tmp = str.replace(s, "");//Replace with empty System.out.println(String.format("Character %s has %2d.", s, str.length()-tmp.length())); str = tmp;//Get the string that has not yet been counted } System.out.println("According to statistics, there are "+i+" characters in this string."); } }