java 用String怎么查询一个字符在字符串里面有多少个
可以使用String的charAt()方法和循环来查询一个字符在字符串中出现的次数。以下是一个例子:
public class Main {
public static void main(String[] args) {
String str = "Hello World";
char targetChar = 'o';
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == targetChar) {
count++;
}
}
System.out.println("The character '" + targetChar + "' appears " + count + " times in the string.");
}
}
输出结果为:`The character 'o' appears 2 times in the string.
原文地址: https://www.cveoy.top/t/topic/ifS2 著作权归作者所有。请勿转载和采集!