遍历char *并将每个char与另一个char比较

我不太精通C,但遇到了问题

  1. 逐个字符地遍历char *
  2. 正确比较单个字符和另一个字符

给定像“ abcda”这样的字符串,我想计算“ a”的数量并返回计数

    #include <stdio.h>
    #include <unistd.h>
    #include <string.h>

    int main(int argc, char** argv){
        char* string_arg;
        int counter = 0;
        if(argc == 2){
            for(string_arg = argv[1]; *string_arg != '\0'; string_arg++){
                printf(string_arg);
                printf("\n");
                /*given abcda, this prints
                abcda                    a
                bcda                     b
                cda        but i want    c
                da                       d 
                a                        a */

                if(strcmp(string_arg, "a") == 0){ //syntax + logical error
                    counter++;
                }
            }
         printf(counter);
         }
         else{
             printf("error");
         }
         return(0);
    }

我也不应该使用strlen()

如何一次正确比较一个字符?

评论
baut
baut
  • arg isn't declared. It seems it should be argc.
  • printf(string_arg); is dangerous because string_arg is an user input, which can contain arbitrary string, which may include %.
  • strcmp() if for comparing strings. You can use simply == to compare characters.
  • printf(counter); is also wrong.
  • } at the end of main function is missing.

示例修复:

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char** argv){
    char* string_arg;
    int counter = 0;
    if(argc == 2){
        for(string_arg = argv[1]; *string_arg != '\0'; string_arg++){
            puts(string_arg);
            /*given abcda, this prints
            abcda                    a
            bcda                     b
            cda        but i want    c
            da                       d 
            a                        a */

            if(*string_arg == 'a'){
                counter++;
            }
        }
        printf("%d", counter);
    }
    else{
        printf("error");
    }
    return(0);
}
点赞
评论