Avatar of hthukral
hthukral

asked on 

How to count the number of different type characters in String ?

Hello Experts,

I have a string of characters which I get from the User :

For Example : Experts Exchange
I want to count how many a's are there, how many b's are there and so on.

What is the best way to do it?  
Java

Avatar of undefined
Last Comment
CEHJ
Avatar of Mick Barry
Mick Barry
Flag of Australia image

loop thru your string incrementing the count:

for (int i=0; i<s.slength(); i++)
{
   char c = s.charAt(i);
   count[(int)c]++;   //u can simplify that if you know the subset of chaters u want to count
}
Avatar of hthukral
hthukral

ASKER

How should I display that these many a's and so on
For Example :
a's - 1
b's - 2
d's - 3
Avatar of Mick Barry
Mick Barry
Flag of Australia image

use another loop to display your counts
Avatar of hthukral
hthukral

ASKER

If I'm in .NET I can simply do something along these lines :
Dictionary<char, int> charCount = new Dictionary<char, int>();

            for (char ch = 'a'; ch <= 'z'; ++ch)

            {

                charCount[ch] = 0;

            }

            charCount[' '] = 0;

 

            string text = "hello hello";

            foreach (char ch in text)

            {

                charCount[ch] = charCount[ch] + 1;

            }

 

            foreach (char ch in charCount.Keys)

            {

                Console.WriteLine(ch + ": " + charCount[ch]);

            }

The above does it what I'm looking for in C#, is there any same way to do in Java.
Avatar of jcoombes
jcoombes
Flag of United Kingdom of Great Britain and Northern Ireland image

If you want to do this in a case-insensitive way then a pretty cludgy way of doing it would be:

Map counts= new HashMap<String, Integer>();

for (int i=0; i<s.length(); i++){
     String tmp= new String(s.charAt(i)).toLower();
     if (counts.containsKey(tmp){
             counts.put(tmp, new Integer(counts.get(tmp) + 1));
     }else{
             counts.put(tmp, new Integer(1));
     }
}

for (String ch : counts.keySet()){
     System.out.println(ch + "'s - " + counts.get(ch));
}
Avatar of jcoombes
jcoombes
Flag of United Kingdom of Great Britain and Northern Ireland image

You might want to take into account non-ASCII characters as well - the version above should also take care of extended characters as well....
Avatar of hthukral
hthukral

ASKER

The above is not happy with me
java:53: '(' or '[' expected
        Map counts = new HashMap<String, Integer>();
Avatar of Mick Barry
Mick Barry
Flag of Australia image

> The above does it what I'm looking for in C#, is there any same way to do in Java.

what i suggested is the same as that :)
you just need to add the 2nd loop to display the array

for (int i=0; i<count.length; i++)
{
   if (count[i]>0) System.out.println(((char)i)+"="+count[i]);
}
Avatar of hthukral
hthukral

ASKER

I want to do the DIctionary or Map way as that solves lot of my other problems, but I guess that compiler is not friendly with me and don't know why it is throing those errors.
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Use an array

char[] counts = new char[26];
for(int i = 0;i < string.length();i++) {
      counts[string.charAt(i) - 'a']++;
}
Avatar of Mick Barry
Mick Barry
Flag of Australia image

> as that solves lot of my other problems

what other problems?
Avatar of hthukral
hthukral

ASKER

I do this and I get

char[] counts = new char[26];
            
            for(int i = 0;i < Function1.length();i++)
            {
                  counts[Function1.charAt(i) - 'a']++;
            }      
            
            for (int i=0; i<counts.length; i++)
            {
                     if (counts[i]>0)
                           System.out.println(((char)i)+"="+counts[i]);
            }
Array oou of bounds exception....At this line counts[Function1.charAt(i) - 'a']++;
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of hthukral
hthukral

ASKER

If I can use Map or Dictionary I don't need to worry for any out of bounds....Can anyone also tell me why Map declaration is not working...

I will increase the points of the question and equally divide among you guys...
Avatar of hthukral
hthukral

ASKER

After running the above code

This was the string : Harsimrat Thukral
and I got this
 =
H=
T=
a=
h=
i=
k=
l=
m=
r=
s=
t=
u=
Avatar of Mick Barry
Mick Barry
Flag of Australia image

> char[] counts = new char[127];

sorry that should have been:

int[] counts = new int[127];

      for(int i = 0;i < Function1.length();i++)
            {
                  counts[Function1.charAt(i)]++;
            }      
           
            for (int i=0; i<counts.length; i++)
            {
                     if (counts[i]>0)
                           System.out.println(((char)i)+"="+counts[i]);
            }
Avatar of Mick Barry
Mick Barry
Flag of Australia image

that code won't have problems with bounds
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You didn't say you're interested in upper case but it can easily be extended to cope with that
Avatar of hthukral
hthukral

ASKER

The code works and how can I get rid of the space...
Avatar of Mick Barry
Mick Barry
Flag of Australia image

int[] counts = new int[127];

      for(int i = 0;i < Function1.length();i++)
            {
                  counts[Function1.charAt(i)]++;
            }      
           
            for (int i=0; i<counts.length; i++)
            {
                     if (i!=' ' && counts[i]>0)
                           System.out.println(((char)i)+"="+counts[i]);
            }
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

It's not particularly interesting to do it case-sensitively so it should be OK to do

string.toLowerCase().charAt(i)
Avatar of Mick Barry
Mick Barry
Flag of Australia image

or:

int[] counts = new int[127];

      for(int i = 0;i < Function1.length();i++)
            {
                  counts[Function1.charAt(i)]++;
            }      
           
            for (int i=0; i<counts.length; i++)
            {
                     if (Character.isLetterOrDigit((char)i) && counts[i]>0)
                           System.out.println(((char)i)+"="+counts[i]);
            }
Avatar of hthukral
hthukral

ASKER

Thanks Guys for all the help.

Really appreciate.

Thanks,
Harsimrat
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

:-)
Java
Java

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

102K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo