4 Replies Latest reply: Oct 3, 2007 2:46 PM by 807600 RSS

    How to scan string of message and detect it character?

    807600
      Well i got string of message like "today is sunny day"
      then i need to come out with an output such as

      a : 2
      o : 1
      d : 2
      m : 0

      something like that which count the character one by one. Please show me some light thanks...
        • 1. Re: How to scan string of message and detect it character?
          807600
          Regex is your light guess.
          import java.util.regex.*;
              
              public class BasicMatch {
                  public static void main(String[] args) {
                      // Compile regular expression
                      String patternStr = "b";
                      Pattern pattern = Pattern.compile(patternStr);
              
                      // Determine if pattern exists in input
                      CharSequence inputStr = "a b c b";
                      Matcher matcher = pattern.matcher(inputStr);
                      boolean matchFound = matcher.find();    // true
              
                      // Get matching string
                      String match = matcher.group();         // b
              
                      // Get indices of matching string
                      int start = matcher.start();            // 2
                      int end = matcher.end();                // 3
                      // the end is index of the last matching character + 1
              
                      // Find the next occurrence
                      matchFound = matcher.find();            // true
                  }
              }
          • 2. Re: How to scan string of message and detect it character?
            Herko_ter_Horst
            I believe the OPs problem is to count the number of times each character occurs in a String, not to find out if one character occurs in the String.

            And I doubt his/her tutor meant for him/her to solve this problem using regexps.

            OP, you haven't posted all requirements I think, but you also need to show you've made an effort to solve this problem yourself.

            You will probably want to use a loop and String.charAt() to get each character from the String. Then you will probably need some sort of collection (I'm thinking a Map) to keep track of the counts for each character.
            • 3. Re: How to scan string of message and detect it character?
              807600
              Hehehe, wiseguy. Think again.
              • 4. Re: How to scan string of message and detect it character?
                807600
                Herko_ter_Horst

                yeah he correct,
                i just wan to count the occurrence of the message in the string
                thanks...i got bit idea after reading it...i think something about string.charAt()