Home>Article>Java> Java counts the number of occurrences of each character in a string

Java counts the number of occurrences of each character in a string

王林
王林 forward
2020-05-28 17:29:42 2826browse

Java counts the number of occurrences of each character in a string

Implementation ideas:

1. Use Scanner to obtain the string entered by the user

2. Create a Map collection, where the key is the character in the string , value is the number of characters

3. Traverse the string and get each character

4. Use the obtained characters to determine whether the key exists in the Map collection

Key exists:

Get the value (number of characters) through the character (key)

value

put (key, value) to store the new value in the Map collection The

key does not exist:

put (key, 1)

5. Traverse the Map collection and output the result

(video tutorial recommendation:java视频)

The specific code is:

public static void main(String[] args) { //1.使用Scanner获取用户输入的字符串 Scanner sc = new Scanner(System.in); System.out.println("请输入一个字符串"); String s = sc.next(); //2.创建Map集合,key是字符串中的字符,value是字符的个数 HashMap map = new HashMap<>(); //3.遍历字符串,获取每一个字符 for (char c : s.toCharArray()) { //4.使用获取到的字符,去Map集合中判断key是否存在 if (map.containsKey(c)) { //key存在 Integer value = map.get(c); value++; map.put(c,value); }else { //key不存在 map.put(c,1); } } //5.遍历Map集合,输出结果 for (Character key:map.keySet()){ Integer value = map.get(key); System.out.println(key+"---"+value); } }

Recommended tutorial:Introduction to java development

The above is the detailed content of Java counts the number of occurrences of each character in a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete