开发者

C character from string shortcut

In javascript I am used to just being able to pick any character from a string like "exm[2]" and it would return to me the third character in 开发者_运维问答a string. In C is there a way to do that or something without a function that requires a buffer?


Since in C "strings" are just character arrays, you can do the same there, too:

char* foo = "Hello World";
printf("%c", foo[4]); // prints o

More to the point, a "string" is just a pointer pointing to the first element of an array of characters ending with a zero character ('\0'). String functions just iterate until they find that null character (which is why they have fun when it's not there) and indexing into an array is just a fancy way of writing some pointer arithmetic:

foo[4]

turns into

*(foo + 4)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜