我正在尝试循环一个 char*str 使用它来找出有多少行:
char *str = "test1\ntest2\ntest3";
int lines = 0;
for(int i = 0 ; i < ?? ; i ++ )
{
if(str[i] == '\n') {
lines++;
}
}
我不确定在 ?? 处放什么,问题是:
1.我的意思是我需要使用 strlen(str) + 1 吗?
2.当str为“test1\ntest2\ntest3\n”时,代码是否仍然计算正确的行数?
顺便说一句,我正在使用gcc,谢谢
最佳答案
每个文字字符串都以 \0
结尾,这是一个空字符。它描述了字符串的结尾
所以, 你可以这样做
for(int i = 0 ; str[i]!='\0' ; i ++ )
关于c - 在字符指针中搜索 '\n 使用 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331435/