开发者

Get a character referenced by index in a C string

I have a string.

char foo[] = "abcdefgh";

I would like to write a for lo开发者_运维百科op, and one by one print out all of the characters:

a
b
c

etc.

This is in C.


Ok, well, this is a question so I'm going to answer it, but my answer is going to be slightly unusual:

#include <stdio.h>

int main(int argc, char** argv)
{
    char string[] = "abcdefghi";
    char* s;

    for ( s=&string[0]; *s != '\0'; s++ )
    {
        printf("%c\n", *s);
    }

    return 0;
}

This is not the simplest way to achieve the desired outcome; however, it does demonstrate the fundamentals of what a string is in C. I shall leave you to read up on what I've done and why.


void main(int argc, char** argv)
{
    char foo[] = "abcdefgh"; 
    int len = strlen(foo);
    int i = 0;
    for (i=0; i < len; i++)
    {
        printf("%c\n", foo[i]);
    }
    return 0;
}


Yet another way

int main(int argc, char *argv[])
{
   char foo[] = "abcdefgh";
   int len = sizeof(foo)/sizeof(char);
   int i = 0;
   for (i=0; i < len; i++) {
      printf("%c\n", foo[i]);
   }
   return 0;
}


I find this method more useful than using strlen(). Because strings in C terminates with a null byte, we can loop them like this :

void loop_str(char *s) {
    for(int i = 0; s[i] != '\0';  i ++) {
        printf("s[%d] -> %c\n", i , s[i]);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜