如何计算java中String中字符的出现次数

时间:2012-03-27 10:37:33

标签: java string decimal

有人能告诉我,我怎么能做一个if子句,说我多久经常在这个String中使用小数分隔符。

即:1234,56,789

6 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:5)

足够简单:

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

答案 2 :(得分:4)

我认为最简单的方法是执行String.split(",")并计算数组的大小。

所以指令看起来像这样:

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

问候,Éric

答案 3 :(得分:2)

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

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

答案 4 :(得分:1)

您不需要任何if子句,只需使用

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

答案 5 :(得分:1)

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());
    }





    }
}