2012-11-06 57 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");