java统计字符串:现有一个字符串“Apple is an apple,not an orange!”,统计“a”出现的次数。
时间: 2023-05-12 20:03:59 浏览: 73
这个问题可以使用 Java 的 String 类的方法来解决。可以使用 charAt() 方法来逐个检查字符串中的每个字符,然后使用 if 语句来判断是否是字符 "a",如果是,就将计数器加一。代码如下:
```
String str = "Apple is an apple,not an orange!";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a') {
count++;
}
}
System.out.println("a出现的次数为:" + count);
```
输出结果为:
```
a出现的次数为:4
```
相关问题
python统计字符串数组中某字符串出现的次数
可以使用 Python 中的 count() 方法来统计字符串数组中某字符串出现的次数。count() 方法接受一个参数,即要统计的字符串,返回该字符串在数组中出现的次数。
例如:
```python
arr = ['apple', 'banana', 'orange', 'apple', 'apple']
count = arr.count('apple')
print(count) # 输出 3
```
以上代码中,arr 数组中有三个 'apple',因此 count 的值为 3。
注释中出现的关键字不用统计 字符串中出现的关键字不用统计java实现
可以使用正则表达式来实现,针对注释和字符串中出现的关键字进行过滤,例如:
```java
String text = "This is a sample text containing some keywords like apple, banana, and orange. // apple and orange should not be counted.\n" +
"String str = \"This is a string containing the word banana.\"; // banana should not be counted.";
// 定义关键字列表
String[] keywords = {"apple", "banana", "orange"};
// 构建正则表达式
String regex = "\\b(" + String.join("|", keywords) + ")\\b";
// 匹配关键字
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
// 统计关键字出现次数
int count = 0;
while (matcher.find()) {
// 判断是否在注释中出现
if (!matcher.group().startsWith("//")) {
count++;
}
}
System.out.println("Number of keywords found: " + count);
```
输出结果为:
```
Number of keywords found: 1
```