samedi 5 septembre 2020

How do I count a substring of characters in a string?

I'm writing a function that takes in a string consisting of 'o', 'g' and 'c' and printing a specific symbol for each character in that string. However, when a substring of 'g's are inside of the string, id like to count how many g's are in a row in the string. For example, if a string is ocggggggo, it will count 6 g's in the string. I've tried a while loop and a for loop but I am getting some runtime errors. Here is the function so far:

void printSymbol(char *str) // takes
{
  int i;
  int k;
  int count;
  for (i = 0; str[i] != '\0'; i++)
  {
     if (str[i] == 'o')
      printf("==========\n");
    if (str[i] == 'c')
      printf(" ~~~~~~~~ \n");
    if (str[i] == 'g') // problem starts here
    {
      for(i = k; str[k] == 'g'; k++) //im using new var for new for loop
     //but want k to keep up with i for the bigger for loop( if that makes sense)
      {
        count++;
      }
      printf("%d\n", count); // printing to make sure right number of g's are being processed.
    }
  }
}

So if an input string was ocgggco, id want the output to be: "==========\n" (minus "") " ~~~~~~~~ \n" "3\n" " ~~~~~~~~ \n" "==========\n"

So, for now, id just like to count how many consecutive g's there are. Im running into problems now such as some 'c' symbols are not printing to the screen when an input is like: ogco. And also some very large number is returning for g. Thanks

Aucun commentaire:

Enregistrer un commentaire