Search code examples
cstringfor-loopif-statementconceptual

Looping through characters in String


I'm looping through each character in this string inputted by the user. The string only consists of 'o' 'g' and 'c'. So for each character, I want to make a certain symbol print to the screen.

I think I can do this by using if statements inside the loop but I'm a little confused on what goes inside the for loop: The following is real and pseudo code idk what goes inside the pseudo-code yet, thus, this question:

So, the first string is inputted by user: say occccgggooo. here's the function I'm working on:

     void printSymbol(char *str)
     {
       int i;
       counter = 0;
       for (i = 0; str[i] != '\0'; i++)
       { //pseudo code begins
         if(o in string)
             printf("/*some symbol*/");
             counter++; //How do i incorporate a counter to move to next character?
         if(g in string)
         .......

And so on. I just don't know what goes inside each if statement to recognize each character in the string.

Also, maybe instead of repeating each if statement I can create some function to call instead? should it just be if (str[i] = 'o') and so on? then have a counter variable move the loop forward?


Solution

  • In C, the strings are null-terminated('\0') char arrays, You are using '/0' which is not valid. Try the below code:

    you can use s[i] to access a character at ith index.

     void printSymbol(char *str)
     {
       int i;
       counter = 0;
       for (i = 0; str[i] != '\0'; i++)
       { //sudo code begins
         if(s[i]=='o')
             printf("/*some symbol*/");
            //How do i incorporate a counter to move to next character?
            // No need to use a separate counter, `i` will be incremented in the for loop.
         if(s[i]=='g')
         .......