2012-02-13 57 views
2

可能重複:
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

如何:

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; 
} 
+0

非常感謝。 :) – 2012-02-13 22:27:32