java 判断字符串在字符串列表中的个数
时间: 2024-09-14 20:07:05 浏览: 56
在Java中,判断一个字符串在字符串列表中的个数可以通过遍历列表并计数的方式实现。以下是一个简单的示例代码,展示了如何计算特定字符串在ArrayList中的出现次数:
```java
import java.util.ArrayList;
public class StringCountExample {
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("apple");
stringList.add("banana");
stringList.add("apple");
stringList.add("orange");
stringList.add("banana");
stringList.add("apple");
String targetString = "apple";
int count = countOccurrences(stringList, targetString);
System.out.println("字符串 '" + targetString + "' 在列表中的个数为: " + count);
}
public static int countOccurrences(ArrayList<String> list, String target) {
int count = 0;
for (String str : list) {
if (target.equals(str)) {
count++;
}
}
return count;
}
}
```
这段代码定义了一个`countOccurrences`方法,它接受一个字符串列表和一个目标字符串作为参数,并返回目标字符串在列表中出现的次数。然后,在`main`方法中,我们创建了一个包含多个字符串的ArrayList,并调用`countOccurrences`方法来计算目标字符串"apple"出现的次数。
阅读全文
相关推荐


















