2015-12-04 178 views
0

我想從C中的字符串中讀取字符的字符,這可以在C上完成,因爲我似乎無法找到任何有關如何做到這一點..從C中的一個字符串中逐字符的讀取

例如:

如果我是從字符讀取字符:

char* name= "Mario"; 

如何才能做到這一點?非常感謝你的幫助!

+3

可能重複[從C中的char \ *獲取單個字符](http://stackoverflow.com/questions/7040501/get-a-single-character-from-a-char-in-c) – Rob

回答

1

只需將其索引爲一個數組即可。 char x = name[0]; /* sets x to 'M' */

請記住,在字符串末尾會有一個空終止符。空終結比較等於0

3

有2種方式在未知長度的空終止字符數組(串)迭代:

for (char *ch = name; *ch; ++ch) { 
    // *ch is the current char 
} 

for (int i=0; name[i]; ++i) { 
    // name[i] is the current char and i the index 
} 

如果長度不知道你可以用strlen得到它並在第二個for循環中使用它作爲i的限制。但strlen將遍歷char數組來查找null終止,這是浪費。