繁体   English   中英

从C中的字符串逐字符读取

[英]Reading character by character from a string in C

我正在尝试从C上的xcode porgram中的字符串逐个字符地读取字符。可以在C上完成此操作,因为我似乎找不到任何有关如何执行此操作的功能。

例如:

如果我要逐字逐句地阅读以下内容:

char* name= "Mario";

如何才能做到这一点? 非常感谢你的帮助!

有两种方法可以迭代长度未知的以空值结尾的char数组(字符串):

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终止符,这很浪费。

像数组一样索引它,例如char x = name[0]; /* sets x to 'M' */ char x = name[0]; /* sets x to 'M' */

请记住,字符串末尾会有一个空终止符。 空终止符比较等于0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM