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

王林
Release: 2020-05-28 17:29:42
forward
2812 people have browsed it

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); } }
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!