Java – Count Character Consecutively in Java

javastring

I'm trying to write a method that returns the number of times char c first appears consecutively in s, even if it's a single occurrence of the character. Even spaces break the consecutive count. So the string "I'm bad at programming." should only return 1, if char c was 'a'.

The code below compiles but doesn't print the correct answers. Just something to show my general logic when it comes to approaching this problem.

public class WordCount
{
  public int countRun( String s, char c )
  {
    int counter = 0;
    for( int i = 0; i < s.length(); i++)
    /*There should be other conditions here that checks for first
      appearance consecutively. I've tried my fair share, but no
      luck on getting correct results.*/
    {
      if( s.charAt(i) == c )
      {
        counter += 1;
      }
    }
    return counter;
  }

  public static void main( String args[] )
  {
    WordCount x = new WordCount();
    System.out.println( x.countRun( "Add dog", 'd' ) ); //should return 2
    System.out.println( x.countRun( "Add dog", 'D' ) ); //should return 0
    System.out.println( x.countRun( "Hope you're happy", 'p' )); //should return 1
    System.out.println( x.countRun( "CCCCCcccC", 'C' )); //should return 5
  }
}

I just need a few pointers (logic-wise or code). Maybe there's a method for Strings that I've never seen before that could make my program much simpler. I have very limited knowledge in programming and in Java.

EDIT: For anyone wondering if this is part of some homework assignment or whatnot, this was a question from a very old midterm. I got it wrong but for some reason but never bothered to ask for the correct answer at the time. I looked at it today and wanted to see if I knew the answer. Looks like I don't.

Best Solution

You could do it in one line:

int result = s.replaceFirst(".*?(" + c + "+).*", "$1").length();

This code uses regex to essentially extract the part of s that is the first contiguous occurrences of c, then gets the length of that.

This will also work for no occurrences, yielding zero.

See live demo.