1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java 统计字符串中每个字符出现的次数(数组或HashMap实现)

java 统计字符串中每个字符出现的次数(数组或HashMap实现)

时间:2020-03-07 13:44:17

相关推荐

java 统计字符串中每个字符出现的次数(数组或HashMap实现)

数组

import java.util.Scanner;public class test {public static void main(String[] args) {Scanner input = new Scanner(System.in);String str1 = input.nextLine();int[] count = new int[52]; //用来存储字母a-z A-Z出现的次数。for(int i=0; i<str1.length(); i++){char tmp = str1.charAt(i); //依次取出每个字母if((tmp>=65&& tmp<=90)||(tmp>=97&& tmp<=122)){int index = tmp - 65; //利用ascii码表,最小结果是0.count[index] = count[index] + 1;}}//循环打印每个字母出现次数for(int j=0; j<count.length; j++){if(count[j]!=0)System.out.println("字母"+(char)(j+65)+"出现次数:"+count[j]);}}}

HashMap

使用HashMap去实现,效率是最高的

有以下几个关键步骤:

将字符串转换为字符数组定义双列集合,存储字符串中字符和字符出现次数遍历数组拿到每一个字符,并存储在集合中(存储过程需要做判断,如果集合中不包含这个键,键的值就为1,如果包含,键的值就在原来基础上加1)

import java.util.HashMap;import java.util.Scanner;public class vowel {public static void main (String args[]){Scanner input = new Scanner(System.in);String s = input.nextLine();//将字符串转换成字符数组char[] arr = s.toCharArray();//定义双列集合,存储字符串字符以及字符出现的次数HashMap<Character,Integer> hm = new HashMap<>();for(char c:arr){//如果集合中不包含这个键,就将该字符当作键,值为1存储,如果集合中包含这个键,就将值增加1存储if(!hm.containsKey(c))hm.put(c, 1);elsehm.put(c,hm.get(c)+1); }for (Character key : hm.keySet())//hm.keySet()代表所有键的集合System.out.println(key + "=" + hm.get(key)); //hm.get(key)根据键获取值}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。