c - 将除\r 之外的所有字符添加到新字符串

标签 c string c-strings chars

这可能是一个非常新的问题,但是我可以解决这个问题,以便将任何字符(\r 除外)添加到我的新字符串 ucontents 中吗?刚才它只添加字符直到\r。我也想在\r 之后添加字符。

void to_unix_line_endings(char* contents, char* ucontents) {
  int i;
  for (i = 0; i < strlen(contents); i++) {
    if(contents[i] != '\r') {
      ucontents[i] = contents[i];
    }
  }
}

char out[5000];
to_unix_line_endings("spaghettiand\rmeatballs", out);
printf("%s\n", out);
// Prints "spaghettiand". I want "spaghettiandmeatballs".

谢谢。

最佳答案

在评论中(在您的答案下),@BLUEPIXY 指出,由于 j 永远不会等于 length,因此 ucontents 将永远不要在 if(j == length) block 中以 NULL 结尾。

因此,尽管您的代码示例(在答案部分中)看起来可以按原样工作,但代码最终会失败。 printf() 需要一个空终止符来标识字符串的结尾。当您正在写入的内存恰好在正确位置没有 NULL 终止符时,它将失败。 (与任何字符串函数一样)。

以下更改将终止您的缓冲区:

void to_unix_line_endings(char* contents, char* ucontents) {
  int i;
  int j = 0;
  int length = strlen(contents);//BTW, good improvement over original post
  for (i = 0; i < length; i++) {
    if(contents[i] != '\r') {
      ucontents[j] = contents[i];
      /*if (j == length) {  //remove this section altogether
        ucontents[j] = '\0';
        break;
      }*/
      j++;//this increment ensures j is positioned 
          //correctly for NULL termination when loop exits
    }
  }
  ucontents[j]=NULL;//add NULL at end of loop
}

关于c - 将除\r 之外的所有字符添加到新字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37100444/

相关文章:

c - 为什么这个宏不运行

在 C 中使用 pow 时,CMake 能否检测到我是否需要链接到 libm?

c - 理解为什么我需要 malloc

javascript - 谁能解释这种关于字符串连接的奇怪 JS 行为?

c - 如何将 char * 字符串转换为指向指针数组的指针并为每个索引分配指针值?

c - 声明的含义

将数组的一部分复制到 C 中的第二个数组

java - 为什么使用replace方法需要重新定义一个String?

python - 检测 Python 字符串是数字还是字母

c - 为字符串动态分配内存