我试图循环一个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 :(得分:7)
每个文字字符串以\0
结尾,这是一个空字符。它描绘了字符串的结尾
所以, 你可以这样做
for(int i = 0 ; str[i]!='\0' ; i ++ )
答案 1 :(得分:3)
扩展已经存在的好答案:循环使用C字符串的惯用方法是
const char *s = "abc\ndef\nghi\n";
int lines = 0;
int nonempty = 0;
while (*s) {
nonempty = 1;
if (*s++ == '\n') lines++;
}
如果您不想将最后一个空行计为单独的行,请添加
if (nonempty && s[-1] == '\n' && lines > 0) lines--;
在while
循环之后。
答案 2 :(得分:1)
取字符串的长度并遍历所有字符。
const unsigned long length=strlen(str);
for(int i = 0 ; i < length ; i ++ )
{
if(str[i] == '\n') {
lines++;
}
}
答案 3 :(得分:1)
无论最后一个字符是否为换行符,以下内容都会产生相同的结果。
char *abc = "test1\ntest2\ntest3";
int lines = 0;
{
bool lastWasNewline = true;
char * p = abc;
for (; *p; ++p) {
if (lastWasNewline) ++lines;
lastWasNewline = *p == '\n';
}
}
答案 4 :(得分:0)
代替??
放置strlen(abc)
并确保#include <string.h>
为了提高效率,
int length= strlen(abc);
然后使用i < length
或使用str[i]!= '\0'
答案 5 :(得分:0)
1.我的意思是我需要使用strlen(str)+ 1?
不,只需对str[i]
使用i < ??
,这会测试是否是终止字符串的0
字符
2.当abc为“test1 \ ntest2 \ ntest3 \ n”时,代码是否仍然计算出正确的行?
不,您的代码假定输入被分成每个缓冲区line[j]
的一个输入行。