可能重复:
check number of a given character occurence in a String
我正在尝试创建一个程序来检查字符串中出现的字符数。 我设法将其转换为ASCII,但我也希望能够计算字符串中出现某个字符或ASCII值的时间。
String myString = "Hello.";
for (int i=0;i<myString.length();i++){
char c = myString.charAt(i);
int j = (int) c;
System.out.println("ASCII OF "+c +" = " + j + ".");
}
除了转换为ASCII之外,如果您还有其他选择,请告知我们。
答案 0 :(得分:0)
这个怎么样:
String myString = "Hello.";
char searchChar = 'l';
int count = 0;
for (int i = 0; i < myString.length(); i++) {
char c = myString.charAt(i);
if (c == searchChar) {
count++;
}
}
System.out.println(count);
这很容易变成一种多次使用的方法:
/**
* Return the number of occurences of a character in the specified String.
*
* @param string the string to search
* @param searchChar the char to search for
* @return the number of occurences of searchChar in string
*/
public int countChars(String string, char searchChar) {
int count = 0;
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (c == searchChar) {
count++;
}
}
return count;
}