如何统计在一个字符串中的字符发生在java

问题描述:

有人可以告诉我,我怎么做一个if-子句,说我多久我在这个字符串中使用十进制分隔符。如何统计在一个字符串中的字符发生在java

即:1234,56,789

+0

你想计算','的出现吗? – 2012-03-27 10:39:33

+0

你的意思是你想要计算字符串中'''的出现次数吗? – beerbajay 2012-03-27 10:40:17

+0

该字符串中的小数点分隔符在哪里? – 2012-03-27 10:41:19

简单:

String number = "1234,56,789"; 
int count = 0; 
for (int i = 0; i < number.length(); i++) 
    if (number.charAt(i) == ',') 
     count++; 
// count holds the number of ',' found 
+1

谢谢你的快速答案。这对我来说很好:) – FabianG 2012-03-27 10:47:22

+1

我在下面的API和它的一个方便的工具中使用了CountMatches方法。 http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html – 2014-07-21 05:37:42

String number = "1234,56,789"; 
int commaCount = number.replaceAll("[^,]*", "").length(); 
+0

这是一个很好的解决方案。 – 2014-09-11 13:41:53

你不需要任何如果子句,只需使用

String s = "1234,56,78"; 
System.out.println(s.split(",").length); 

我觉得simpliest方式将执行String.split(",")并计算数组的大小。

所以指令预订购这个样子:

String s = "1234,56,789"; 
int numberofComma = s.split(",").length; 

的问候,埃里克

如果可以使用非if子句,你可以这样做:

int count = number.split(",").length 

public class OccurenceOfChar { 

public static void main(String[] args) throws Exception { 
    // TODO Auto-generated method stub 

    BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
    System.out.println("Enter any word"); 
    String s=br.readLine(); 

    char ch[]=s.toCharArray(); 
    Map map=new HashMap(); 


    for(int i=0;i<ch.length;i++) 
    { 
     int count=0; 
     for(int j=0;j<ch.length;j++) 
     { 
      if(ch[i]==ch[j]) 
       count++; 
     } 
    map.put(ch[i], count); 


    } 
    Iterator it=map.entrySet().iterator(); 
    while(it.hasNext()) 
    { 
     Map.Entry pairs=(Map.Entry)it.next(); 
     System.out.println("count of "+pairs.getKey() + " = " + pairs.getValue()); 
    } 





    } 
}