使用两个for循环计算字符串中的字母
我必须读取字符串"hello world"
并仅使用for循环输出每个字母的频率。 教练暗示我需要使用两个循环并给我们以下代码开始:
int ch, count; for (ch ='a'; ch 0 }
编辑:我想我会解决这个问题并发布一年前我找到的解决方案,因为这个问题已经得到了相当多的点击率。
int count; int value; for (int i=65; i<91; i++) { count=0; for (int j=0; j0) System.out.println((char)i+" -- "+count); }
在第二个for循环中,只需遍历字符串的每个字符,并将其与first for循环的当前字符进行比较。
(不是我会做的解决方案,只是跟着你的导师提示)
另一种方法是将值存储在地图中,其中字符为关键字,而出现的计数器为值。
HashMap map = new HashMap<>(); for (int ii=0; ii
更新:
//iterating on the map to output values: for (char key : map.keySet()) { System.out.println(key+": "+map.get(key)); }
我会用一个简单的数组。 只需将每个字母转换为索引,然后在该索引处递增数组。
int letters[26]; int index = ch - 'a'; letters[index]++;
为了建立sdasdadas的评论和Jean的答案:
外部for循环将旋转字母表中的每个字符,保持计数(每次外循环执行时都需要重置。)内部循环循环“hello world”字符串,如果字符作为字符,则递增计数器找到外部for循环的当前参数。
更新我不能评论安德烈的答案,但我可以提供一些伪代码来解决我认为你在关于计数器的评论中的意思。
int i; for (ch characterOuter : alphabet){ //for each character in the alphabet i = 0 //i starts at zero, and returns to zero for each iteration <-----THIS for (ch characterInner : "hello world"){ if (characterOuter == characterInner){ i++; //increase i by 1 <-----AND THIS }//end if }//end innerfor if (i > 0) { print(characterOuter + " -- " + i); } //end if; <---------------- this if statement was missing }//end outer for
另外,请看这个问题 。
int count; int value; for (int i=65; i<91; i++) { count=0; for (int j=0; j0) System.out.println((char)i+" -- "+count); }