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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9887918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:47:13  来源:igfitidea点击:

How to count occurrences of a character in a String in java

javastringdecimal

提问by FabianG

Can someone tell me, how can I do an if-clause, that say me how often I used the decimal seperator in this String.

有人能告诉我,我怎么能做一个 if 子句,说我在这个字符串中使用十进制分隔符的频率。

i.e.: 1234,56,789

即:1234,56,789

回答by Jim

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

回答by óscar López

Simple enough:

足够简单:

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

回答by óscar López

I think the simpliest way is to exucute a String.split(",")and count the size of array.

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

So the instruction willl look like this :

所以指令看起来像这样:

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

Regards, éric

问候,埃里克

回答by Guillaume USE

If you can use an non-if-clause, you can do :

如果您可以使用非 if 子句,则可以执行以下操作:

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

回答by pushp priyadarshi

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





    }
}

回答by Chandra Sekhar

You don't need any if-clause, just use

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

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