Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count Character Consecutively in Java

Tags:

java

string

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.

like image 364
Bob Avatar asked Dec 27 '22 03:12

Bob


2 Answers

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.

like image 184
Bohemian Avatar answered Jan 11 '23 13:01

Bohemian


Add a flag, and break out of the loop when you have found one matching character, then find "anything else". Maybe not the most compact or elegant, but true to the original code. Tested, and produces 2,0,1,5 as expected.

public int countRun( String s, char c )
  {
    int counter = 0;
    boolean foundOne = false;
    for( int i = 0; i < s.length(); i++)
    {
      if( s.charAt(i) == c )
      {
        counter += 1;
        foundOne = true;
      }
      else {
        if(foundOne) break;
      }
    }
    return counter;
  }

It occurs to me that counter>0 is an equivalent condition to foundOne==true; that would allow you to simplify the code to:

public int countRun( String s, char c )
  {
    int counter = 0;
    for( int i = 0; i < s.length(); i++)
    {
      if( s.charAt(i) == c )  counter++;
      else if(counter>0) break;
    }
    return counter;
  }

The logic is a tiny bit harder to follow this way, as the variable name foundOne is self-documenting. But per other posts, "small is beautiful" too...

like image 30
Floris Avatar answered Jan 11 '23 14:01

Floris