How to iterate over a string in C?

前端 未结 13 1234
花落未央
花落未央 2020-11-28 06:43

Right now I\'m trying this:

#include 

int main(int argc, char *argv[]) {

    if (argc != 3) {

        printf(\"Usage: %s %s sourcecode inpu         


        
相关标签:
13条回答
  • 2020-11-28 06:57

    Just change sizeof with strlen.

    Like this:

    char *source = "This is an example.";
    int i;
    
    for (i = 0; i < strlen(source); i++){
    
        printf("%c", source[i]);
    
    }
    
    0 讨论(0)
  • 2020-11-28 06:59

    One common idiom is:

    char* c = source;
    while (*c) putchar(*c++);
    

    A few notes:

    • In C, strings are null-terminated. You iterate while the read character is not the null character.
    • *c++ increments c and returns the dereferenced old value of c.
    • printf("%s") prints a null-terminated string, not a char. This is the cause of your access violation.
    0 讨论(0)
  • 2020-11-28 06:59

    This should work

     #include <stdio.h>
     #include <string.h>
    
     int main(int argc, char *argv[]){
    
        char *source = "This is an example.";
        int length = (int)strlen(source); //sizeof(source)=sizeof(char *) = 4 on a 32 bit implementation
        for (int i = 0; i < length; i++) 
        {
    
           printf("%c", source[i]);
    
        }
    
    
     }
    
    0 讨论(0)
  • 2020-11-28 07:00

    sizeof(source) returns sizeof a pointer as source is declared as char *. Correct way to use it is strlen(source).

    Next:

    printf("%s",source[i]); 
    

    expects string. i.e %s expects string but you are iterating in a loop to print each character. Hence use %c.

    However your way of accessing(iterating) a string using the index i is correct and hence there are no other issues in it.

    0 讨论(0)
  • 2020-11-28 07:02

    Replace sizeof with strlen and it should work.

    0 讨论(0)
  • 2020-11-28 07:02

    You need a pointer to the first char to have an ANSI string.

    printf("%s", source + i);
    

    will do the job

    Plus, of course you should have meant strlen(source), not sizeof(source).

    0 讨论(0)
提交回复
热议问题