Hi Everybody,

I was wondering if there was a way to find the most common letter/number/special symbol in a string. Thanks!!

Thanks again in advanced,
C++

Recommended Answers

All 11 Replies

static int countChars( String str, char searchChar ) {
                  // Count the number of times searchChar occurs in
                  // str and return the result.
                int i;     // A position in the string, str.
                char ch;   // A character in the string.
                int count; // Number of times searchChar has been found in str.
                count = 0;
                for ( i = 0;  i < str.length();  i++ ) {
                    ch = str.charAt(i);  // Get the i-th character in str.
                    if ( ch == searchChar )
                       count++;
                }
                return count;
            }

>static int countChars( String str, char searchChar )
This only returns the count for a single character. So to find the most common character, not only would you be forced to call countChars for every character in the string, you would also need to find a character with the largest count. That's a little too much work for my tastes, and it's not very efficient either.

How about a complete program that solves the problem with only eight more logical lines than your single method and is more than twice as fast:

import java.util.*;

public class scratch {
  public static void main(String[] args)
  {
    HashMap<Character, Integer> h = new HashMap<Character, Integer>();
    String s = "This is a test that find the most common character";
    String unique = new String();

    for ( int i = 0; i < s.length(); i++ ) {
      if ( h.containsKey ( s.charAt ( i ) ) ) {
        h.put ( s.charAt ( i ), (int)h.get ( s.charAt ( i ) ) + 1 );
      } else {
        h.put ( s.charAt ( i ), 1 );
        unique += s.charAt ( i );
      }
    }

    Set<Map.Entry<Character, Integer>> freq = h.entrySet();
    Iterator<Map.Entry<Character, Integer>> it = freq.iterator();

    while ( it.hasNext() ) {
      Map.Entry<Character, Integer> item = it.next();
      System.out.println ( item.getKey() + ": " + item.getValue() );
    }
  }
}

With only a little more effort you can print out just the most common character. ;)

I've been outsmarted by a girl. I deserve to die. :sad:

Made it a bit smarter, couldn't help tinker and use some more features of the Tiger :)
The explicit cast to int Narue used was not needed, and the iteration can be performed using the new for-each loop in 4 lines less code than she used ;)

import java.util.*;

public class Scratch {
  public static void main(String[] args)
  {
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    String theString = "This is a test that find the most common character";
    String unique = new String();

    for (int i = 0; i < theString.length(); i++) {
      if ( map.containsKey(theString.charAt(i))) {
        map.put (theString.charAt(i), map.get(theString.charAt(i)) + 1 );
      } else {
        map.put (theString.charAt(i), 1);
        unique += theString.charAt (i);
      }
    }
    for(Map.Entry item:map.entrySet())
        System.out.println(item.getKey() + ": " + item.getValue());
  }
}

>couldn't help tinker and use some more features of the Tiger
I also notice you didn't like my intuitive and obvious name for the HashMap, h. :cheesy:

indeed. I'd have changed it to m except that might be seen as slightly pickish :)
Of course using JBuilder it's extremely easy to replace all instances of a name with another, just click on the block edit button and change any one of them to change them all :cheesy:

>I'd have changed it to m except that might be seen as slightly pickish
x is the better choice anyway, or my personal favorite identifier for "a chunk of memory that holds something": shtoobie. My coworkers love it when I give them code with declarations like this:

map< vector<string, double>, set<int, string> > *shtoobie.

:lol:

You guys, need to thank me for softening the program up for you.

Or try to get the better of them by creating a set of types I11I and II11 with each members l11l and ll11 (for example).
Of course even better in an editor using a sans-serif font like Arial ;)

import java.util.*;

public class RepeatedExample {
  public static void main(String[] args)
  {
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    String theString = "aaba";
     for (int i = 0; i < theString.length(); i++) {
      if ( map.containsKey(theString.charAt(i))) {
        map.put (theString.charAt(i), map.get(theString.charAt(i)) + 1 );
      } else {
        map.put (theString.charAt(i), 1);
        }
    }
    for(Map.Entry item:map.entrySet())
        System.out.println(item.getKey() + ": " + item.getValue());
  }
}

Hello DeepakNarang

Here at DaniWeb we try to help people learn Java and develop their Java skills. We do NOT do people's homework for them. Your post explains and teaches nothing. In future please help by pointing people in the right direction - eg tell them which classes and methods they should read about, or give them some sample code that they will have to understand and adapt to their needs. If you feel you should correct someone's code then that's useless if you don't explain what you changed and why you changed it as you did. If you need to explain with actual code then explain why you coded it the way you did. Don't just spoon-feed them a solution to copy and paste.

But anyway - this thread is 8 years old, so it's too late!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.