我一直在学习一些聪明的 C 函数,它们需要一个循环,但不需要执行循环体(如 strcpy()
),因此只有一行。
只是出于兴趣,有没有什么办法可以像这样减少将所有 \n
换行符替换为一行的空格?
目前我有
char* newline_index;
while (newline_index = strchr(file_text, '\n'))
{
*newline_index = ' ';
}
我想做这样的事情:
while (*strchr(file_text, '\n') = ' ');
当然,当 strchr 返回 null 时,我会尝试取消引用空指针。
我知道使用 strchr 是作弊,因为它包含更多代码,但我想看看是否有仅使用标准 C 函数的单行方法。
编辑:在一些帮助下,这是我想出的最好的办法:
char* newline_index;
while ((newline_index = strchr(file_text, '\n')) && (*newline_index = ' '))
最佳答案
我建议使用以下代码。以下代码在一行中,它避免了函数 strchr()
的调用:
char* p = file_text;
while(*p!='\0' && (*p++!='\n' || (*(p-1) = ' ')));
您还可以使用 for
循环:
char* p;
for(p = file_text; *p!='\0' && (*p!='\n' || (*p = ' ')); p++);
对于您提供的解决方案:
char* newline_index;
while ((newline_index = strchr(file_text, '\n')) && (*newline_index = ' '))
以这种方式调用 strchr()
将使搜索从你的 file_text
的开头开始,每次你想搜索 '\n'
。
我建议将其更改为:
char* newline_index = file_text;
while ((newline_index = strchr(newline_index, '\n')) && (*newline_index = ' '))
这将允许 strchr()
从最后一个位置而不是从头开始继续搜索 '\n'
。
即使进行了优化,strchr()
函数的调用也需要时间。所以这就是为什么我提出了一个不调用strchr()
函数
关于C字符一行替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16454405/