简体   繁体   中英

Using a while loop to count instances in a string in java

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

h i, I need h elp! 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

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, '!');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM