在String中查找重复字符并使用Java计算出现次数 [英] Find duplicate characters in a String and count the number of occurances using Java

查看:162
本文介绍了在String中查找重复字符并使用Java计算出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何找到字符串中字符的出现次数?

How can I find the number of occurrences of a character in a string?

例如:快速的棕色狐狸跳过懒狗

For example: The quick brown fox jumped over the lazy dog.

下面是一些示例输出,

'a' = 1
'o' = 4
'space' = 8
'.' = 1


推荐答案

import java.io.*;
public class CountChar 
{

    public static void main(String[] args) throws IOException
    {
      String ch;
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Enter the Statement:");
      ch=br.readLine();
      int count=0,len=0;
        do
        {  
          try
          {
          char name[]=ch.toCharArray();
              len=name.length;
              count=0;
              for(int j=0;j<len;j++)
               {
                  if((name[0]==name[j])&&((name[0]>=65&&name[0]<=91)||(name[0]>=97&&name[0]<=123))) 
                      count++;
               }
              if(count!=0)
                System.out.println(name[0]+" "+count+" Times");
              ch=ch.replace(""+name[0],"");          
          }
          catch(Exception ex){}
        }
        while(len!=1);
   }

}




输出



Enter the Statement:asdf23123sfsdf

a 1 Times

s 3 Times

d 2 Times

f 3 Times

这篇关于在String中查找重复字符并使用Java计算出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆