计算ArrayList中一系列字符串中出现的某个字母的数量 [英] Counting the number of a certain letter appears in series of strings in an ArrayList
问题描述
我有一个 ArrayList 以做盘子"的形式存储笔记(字符串).我有一个带有方法的笔记类,该方法应该遍历 ArrayList 中的所有笔记并计算某个字母出现的次数.这是我目前写的方法:
I have an ArrayList that stores notes (strings) in the form of "do the dishes". I have a notes class with a method that is supposed to go through all the notes in the ArrayList and count the number of times a certain letter appears. This is the method I have written so far:
public int countNumberOf(String letter) {
int count = 0;
for (int i = 0; i < notes.size(); i++) {
String note = (notes.get(i));
for (int j = 0; i < note.length(); i++) {
String letterTemp = note.substring(i, i);
if (letterTemp.equalsIgnoreCase(letter)) {
count++;
}
}
}
return count;
}
但是,当我运行该程序时,即使我知道它出现在 ArrayList 中,字母a"出现的次数也为零.我做错了什么?
However, when I run the program, I'm getting zero for the number of times the letter "a" appears even though I know it's present in the ArrayList. What am I doing wrong?
推荐答案
与将 String
传递给方法并执行 substring
不同,您始终可以访问和比较字符,例如:
Instead of passing a String
to a method and doing a substring
, you can always access and compare the characters, e.g.:
public int countNumberOf(char letter) {
...
String letterTemp = note.charAt(i);
if (letter == letterTemp) {
count++;
}
另一个例子:
public static int countOccurrences(String text, char character) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == character) {
count++;
}
}
return count;
}
这篇关于计算ArrayList中一系列字符串中出现的某个字母的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!