统计一个字符串中指定字符出现的次数java
时间: 2023-08-08 09:08:46 浏览: 62
可以使用Java的字符串方法 `charAt()` 和 `length()` 来遍历字符串并计数指定字符出现的次数。以下是一个示例代码:
```java
public static int countChar(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
```
该方法接受一个字符串和一个字符作为参数,并返回指定字符在字符串中出现的次数。您可以按如下方式调用该方法:
```java
String str = "Hello World!";
char c = 'o';
int count = countChar(str, c);
System.out.println("Character '" + c + "' appears " + count + " times in the string.");
```
输出结果应该是:`Character 'o' appears 2 times in the string.`
相关问题
统计指定子字符串在字符中出现的次数Java实现
可以使用Java中的String类的indexOf()和substring()方法来实现统计指定子字符串在字符串中出现的次数。具体实现如下:
```java
public static int countSubstring(String str, String subStr) {
int count = 0;
int index = 0;
while ((index = str.indexOf(subStr, index)) != -1) {
count++;
index += subStr.length();
}
return count;
}
```
该方法接收两个参数:原始字符串和要统计的子字符串。它使用一个while循环来遍历整个字符串,每次使用indexOf()方法查找子字符串出现的位置,如果找到了就将计数器加1,然后将查找的起始位置更新为当前位置加上子字符串长度,以便查找下一个子字符串。
示例用法:
```java
String str = "hello world, world is beautiful!";
String subStr = "world";
System.out.println(countSubstring(str, subStr)); // 输出2
```
注意:该方法不区分大小写,如果需要区分大小写可以使用String的equalsIgnoreCase()方法和substring()方法。
Java统计指定字符串在对应字符串中出现的次数
可以使用Java中的indexOf()和substring()方法来统计指定字符串在对应字符串中出现的次数。具体实现如下:
```java
public static int countOccurrences(String str, String target) {
int count = 0;
int index = 0;
while ((index = str.indexOf(target, index)) != -1) {
count++;
index += target.length();
}
return count;
}
```
其中,str为对应字符串,target为指定字符串。使用indexOf()方法查找target在str中第一次出现的位置,若返回值不为-1,则count加1,然后继续在str中查找target,直到找不到为止。注意,每次找到一个target后,index需要加上target的长度,以便查找下一个target的位置。
调用该方法的示例代码如下:
```java
String str = "hello world, world is beautiful";
String target = "world";
int count = countOccurrences(str, target);
System.out.println(count); // 输出2
```