0

Problem

How many instances of a certain character are there between the beginning of the string and a break point?

The break point is the first instance of another character.

For example, my string could be

hi, I need help! with this problem!

and I want to use a while loop to count the h s from the beginning to the !, so the output would be 2.

I am extremely new to java so I only know how to use a while loop to count up to a certain number but I don't know how to break or how to ask it to count just a certain character. Any hint in the right direction would be great.

My idea is to do something like:

while(character equals 'h', count)
else(don't count)
break if(character equals !)
print

But I don't know how to translate that to java

2
  • Your idea sounds right. Try it. Read tutorials about while loops, conditionals and variables. Commented Jan 30, 2016 at 20:22
  • 1
    You should do your homework first. This is straightforward. Commented Jan 30, 2016 at 20:41

1 Answer 1

2

Here is a quick code snippet:

/**
 * Method Name: countChars
 * Arguments: 4 (Original String, Character to be found, Start Index, 
 *               Stop/Terminate Character)
 * Returns: Character Count
**/
public int countChars(String str, char c, int start, char e) {
     char[] chr = str.toCharArray();
     /* Initialize Count Counter */
     int count = 0;

     /* Initialize Counter With Start Index */
     int i = start;
     /* Iterate String For Positive Matches */
     while(i < chr.length) {
          /* Core Logic */
          if(chr[i] == e) {
               /* Terminate Character Found : Break Loop */
               break;
          } else if(chr[i] == c) {
               /* Match Found : Increment The Counter */
               count++;
          }
          /* Increment Loop Counter */
          ++i;
     }

     /* Return Character Count */
     return count;
}

You can call this method as follows:

int count = countChars(myString, 's', 0, '!');
Sign up to request clarification or add additional context in comments.

6 Comments

Code dumps without explanation are not helpful to a beginner. Please explain what you are doing in this code.
Also, I don't think this quite does what is being asked - it should go to the first instance of "another character", not within a certain range.
@Andy Thanks for your response. Added Comments & Changed the Terminate Condition.
Those for loops makes sense to me and I've done some before. The book I'm working from specifically asks for a while loop though and to use a string variable, any way to do it that way?
@Nick94107 Changed it to use while instead of for.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.