2012-11-06 101 views

回答

2

使用正則表達式[g]找到char和計算結果如下:

Pattern pattern = Pattern.compile("[g]"); 
    Matcher matcher = pattern.matcher("engineering"); 
    int countCharacter = 0; 
    while(matcher.find()) { 
     countCharacter++; 
    } 
    System.out.println(countCharacter); 

如果你想不區分大小寫計數,在模式中使用正則表達式作爲[gG]

6

我會用一個PatternMatcher

String string = "engineering"; 
Pattern pattern = Pattern.compile("([gG])"); //case insensitive, use [g] for only lower 
Matcher matcher = pattern.matcher(string); 
int count = 0; 
while (matcher.find()) count++; 
0

您可以嘗試以下操作:

String str = "engineering"; 
int letterCount = 0; 
int index = -1; 
while((index = str.indexOf('g', index+1)) > 0) 
    letterCount++; 
System.out.println("Letter Count = " + letterCount); 
22

試試這個

int count = StringUtils.countMatches("engineering", "e"); 

更多StringUtils可以從這個問題可以瞭解到: How do I use StringUtils in Java?

+0

你從哪裏得到'StringUtils'? –

+2

請檢查commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html – sunleo

4

儘管正則表達式可以正常工作,但在這裏並不需要。你可以簡單地使用for-loop來爲一個角色維護一個count

您將需要您的字符串轉換爲字符數組: -

String str = "engineering"; 
    char toCheck = 'g'; 
    int count = 0; 

    for (char ch: str.toCharArray()) { 
     if (ch == toCheck) { 
      count++; 
     } 
    } 
    System.out.println(count); 

或者,你也可以做到這一點無需轉換charArray: -

for (int i = 0; i < str.length(); i++) { 
    if (str.charAt(i) == toCheck) { 
     count++; 
    } 
} 
+0

請檢查是否有計數不匹配。 – sunleo

+0

@sunleo ..對於哪些代碼?那麼,他們都工作得很好。剛剛檢查過它。 –

+0

@sunleo ..請嘗試一下。在我的情況下,他們都給了'3'。 –

3
String s = "engineering"; 
char c = 'g'; 
s.replaceAll("[^"+ c +"]", "").length(); 
+0

注意,如果'char c'來自用戶輸入,這種方法很容易受到正則表達式的注入。 (類似於SQL注入) – Tuupertunut

0

你可以通過它循環,並保持你想要的字母數。

public class Program { 
    public static int countAChars(String s) { 
     int count = 0; 
     for(char c : s.toCharArray()) { 
      if('a' == c) { 
       count++; 
      } 
     } 
     return count; 
    } 
} 

或者您可以使用StringUtils來計數。

int count = StringUtils.countMatches("engineering", "e"); 
22

我知道這是老問題,但就是沒有得到回答的選項,這是很簡單的一行:

int count = string.length() - string.replaceAll("g","").length() 
+1

我認爲你應該將beginIndex和endIndex添加到子字符串 –

1

這是一個非常非常古老的問題,但是這可能幫助別人( 「_」)

您可以只需在使用此代碼

public static void main(String[] args){ 
    String mainString = "This is and that is he is and she is"; 
    //To find The "is" from the mainString 
    String whatToFind = "is"; 
    int result = getCountOf(mainString, whatToFind); 
    System.out.println(result); 
} 

public static int countMatches(String mainString, String whatToFind){ 
    String tempString = mainString.replaceAll(whatToFind, ""); 
    //this even work for on letter 
    int times = (mainString.length()-tempString.length())/whatToFind.length(); 

    //times should be 4 
    return times; 
} 
0

使用org.apache.c ommons.lang3包使用StringUtils類。 下載jar文件並將其放置到Web應用程序的lib文件夾中。

int count = StringUtils.countMatches("engineering", "e");