循环遍历 String 中的字符

Looping through characters in String

我正在遍历用户输入的字符串中的每个字符。该字符串仅由 'o' 'g' 和 'c' 组成。所以对于每个字符,我想在屏幕上打印一个特定的符号。

我想我可以通过在循环内使用 if 语句来做到这一点,但我对 for 循环内的内容有点困惑:以下是真实代码和伪代码,不知道伪代码中的内容,因此,这个问题:

因此,第一个字符串由用户输入:say occccgggooo。 这是我正在处理的功能:

     void printSymbol(char *str)
     {
       int i;
       counter = 0;
       for (i = 0; str[i] != '[=10=]'; 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)
         .......

等等。我只是不知道每个 if 语句中包含什么来识别字符串中的每个字符。

此外,也许我可以创建一些函数来调用而不是重复每个 if 语句?应该只是 if (str[i] = 'o') 等等吗?然后让计数器变量使循环向前移动?

在 C 中,字符串是 null-terminated('\0') 字符数组, 您正在使用无效的“/0”。 试试下面的代码:

您可以使用 s[i] 访问 ith 索引处的字符。

 void printSymbol(char *str)
 {
   int i;
   counter = 0;
   for (i = 0; str[i] != '[=10=]'; 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')
     .......