开发者

Get a character referenced by index in a C string

开发者 https://www.devze.com 2023-01-31 00:14 出处:网络
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:

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

精彩评论

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

关注公众号