C字符一行替换

标签 c string while-loop

我一直在学习一些聪明的 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/

相关文章:

c++ - 遍历字符串会导致段错误

c - 如何在格式字符串攻击中将值写入地址

c - 为什么在c编程中通过putchar输入超过1个字符时putchar不只显示1个字符?

PHP 如果文件夹存在为每个子文件夹做一个循环

c - 使用 X11 编译时未解析的外部 typedef

c - Posix 与 System V 中基于共享内存的管道之间的区别?

java - while 仅循环

python - while 循环中的一行代码只执行一次

c - 带约束的迷宫求解

c - libcurl HTTPS POST 数据发送?