怎么用String的方法判断字符串中字符出现的次数
时间: 2024-04-30 09:23:52 浏览: 5
可以使用String类的charAt()方法和循环来遍历字符串中的每个字符,然后使用计数器来记录每个字符出现的次数。下面是一个示例代码:
```java
String str = "hello world";
int count = 0;
char ch = 'l';
for(int i=0; i<str.length(); i++) {
if(str.charAt(i) == ch) {
count++;
}
}
System.out.println("The character " + ch + " appears " + count + " times in the string.");
```
这段代码会输出:
```
The character l appears 3 times in the string.
```
可以根据需要将以上代码封装成一个方法来判断任意字符在字符串中出现的次数。
相关问题
怎么用substring()方法判断字符串中字符出现的次数
使用substring()方法判断字符串中字符出现的次数需要配合使用indexOf()方法和循环结构,具体代码如下:
```
String str = "hello world";
char ch = 'l';
int count = 0;
int index = str.indexOf(ch);
while (index != -1) {
count++;
index = str.indexOf(ch, index + 1);
}
System.out.println("字符 " + ch + " 出现的次数为:" + count);
```
解释如下:
- 首先定义字符串和需要判断出现次数的字符;
- 然后定义计数器count,初始化为0;
- 使用indexOf()方法查找字符串中字符的位置,如果找到返回字符位置,如果没找到返回-1;
- 如果找到了字符位置,计数器count加1,然后继续寻找下一个字符的位置;
- 一直循环寻找到最后一个字符的位置,计数器就是该字符在字符串中出现的次数。
使用substring()方法判断字符串中字符出现的次数不太方便,建议使用上述方法。
c++ 判断string某个字符串出现次数
可以使用`std::count`函数来判断一个字符串中某个子串出现的次数,示例代码如下:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "hello world, hello C++";
std::string sub = "hello";
int count = std::count(str.begin(), str.end(), sub.begin(), sub.end());
std::cout << "The substring \"" << sub << "\" appears " << count << " times in the string \"" << str << "\"." << std::endl;
return 0;
}
```
输出结果为:
```
The substring "hello" appears 2 times in the string "hello world, hello C++".
```