Page 1 of 2 12 LastLast
Results 1 to 10 of 12

Thread: Count the number of occurences of substring in a string in Java

  1. #1
    Join Date
    Jul 2007
    Beans
    395

    Count the number of occurences of substring in a string in Java

    Does anybody know the simplest and cleanest way of of counting the number of times a substring occurs in a string in Java?

    Is there also a way to accomplishing the task using the regular expressions?

  2. #2
    Join Date
    Jan 2006
    Beans
    Hidden!
    Distro
    Ubuntu 10.10 Maverick Meerkat

    Re: Count the number of occurences of substring in a string in Java

    I believe that you can, one of the objects returns an array of matches. I don't remember exactly, but it is doable (unless I am not remembering something).
    I am infallible, you should know that by now.
    "My favorite language is call STAR. It's extremely concise. It has exactly one verb '*', which does exactly what I want at the moment." --Larry Wall
    (02:15:31 PM) ***TimToady and snake oil go way back...
    42 lines of Perl - SHI - Home Site

  3. #3
    Join Date
    Aug 2006
    Location
    60°27'48"N 24°48'18"E
    Beans
    3,458

    Re: Count the number of occurences of substring in a string in Java

    Regexps are probably the easiest one... you just call "find" as many times as it returns something, and count those.
    LambdaGrok. | #ubuntu-programming on FreeNode

  4. #4
    Join Date
    Sep 2006
    Beans
    2,914

    Re: Count the number of occurences of substring in a string in Java

    see here for some suggestions

  5. #5
    Join Date
    Aug 2006
    Location
    Pittsburgh, PA
    Beans
    424
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Count the number of occurences of substring in a string in Java

    You could use String.indexOf(string,start)

    Like so:


    Where str is the string you are searching in and findStr is what you are looking for.

    Code:
    lastIndex = 0;
    count =0;
    
    while(lastIndex != -1){
    
           lastIndex = str.indexOf(findStr,lastIndex);
    
           if( lastIndex != -1){
                 count ++;
          }
    }
    That would do exactly what you need. There may be more efficient solutions out there like regular expressions though. This one is decent though.
    Last edited by themusicwave; April 12th, 2008 at 04:29 AM. Reason: Forgot my code tags

  6. #6
    Join Date
    Jul 2007
    Beans
    395

    Re: Count the number of occurences of substring in a string in Java

    Thank you all. Everything was very helpful. I stuck with the regular expression option.

  7. #7
    Join Date
    Apr 2007
    Location
    Hungary
    Beans
    136
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: Count the number of occurences of substring in a string in Java


  8. #8
    Join Date
    Aug 2010
    Beans
    1

    Re: Count the number of occurences of substring in a string in Java

    Quote Originally Posted by themusicwave View Post
    Code:
           lastIndex = str.indexOf(findStr,lastIndex);
    You would have to change this line to ensure subsequent iterations don't just keep looking at the previous result, but yeah, regular expressions sound like the go since I'm wanting to perform validation tasks.

    Thanks.

    Update:
    Wanting to count the number of commas in a line of CSV text.
    Code:
    import java.util.regex.Pattern;
    
    public static Boolean isValid(final String s) {
            String regex = "[^,]*,[^,]*,[^,]*,[^,]*,[^,]*";
    
            return Pattern.matches(regex, s);
    }
    Last edited by sav991; August 4th, 2010 at 04:54 AM. Reason: Problem-proper solved

  9. #9
    Join Date
    Apr 2008
    Beans
    507

    Re: Count the number of occurences of substring in a string in Java

    Quote Originally Posted by sav991 View Post
    Wanting to count the number of commas in a line of CSV text.

    I always liked split for this task ...

    Code:
    String s = "a,b,c,d";
    System.out.println(s.split(",").length-1);
    Sure we are creating an array but I don't care

    Obviously this doesnt cater for quoted commas etc but you can mod the regex to suit.
    Go you good thing!

  10. #10
    Join Date
    Nov 2009
    Beans
    1,081

    Re: Count the number of occurences of substring in a string in Java

    Quote Originally Posted by sav991 View Post
    Update:
    Wanting to count the number of commas in a line of CSV text.
    Regexes might be overkill for counting commas.

    If you don't care about commas in quoted strings, or any escape characters, you can just loop over the results of stringVariable.toCharArray() incrementing a variable whenever you see a comma. Linear time, constant space cost.


    If you do care, something like

    Code:
    boolean escapeMode = false;  // \ = escape next character
    boolean quoteMode  = false;  // "foo"
    int count = 0;
    
    // note:  below does necessarily not handle all 
    // multi-byte Unicode characters; it also does not handle
    // quote characters except "
    //
    // if that is a concern, use String's getCodePointAt() 
    // and Character's toChars(), as well as Character's 
    // getType() for identifying initial/final quotes... 
    
    for (char c : stringVariable.toCharArray()) {
      if (escapeMode) {
         // Only good for one character.
         escapeMode = false;
      } else if (c == '\\') {
         // next character is treated as normal even if special
         // even if we're in a quote; this allows a quote within
         // a quoted string
         escapeMode = true;
      } else if (c  == '"') {
         quoteMode = !quoteMode;
      } else if ((!quoteMode) && (c == ',')) {
         count++;
      }
    }

Page 1 of 2 12 LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •