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

Add all characters except \r to new string

这可能是一个非常新的问题,但我可以解决这个问题以便将任何字符(\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。

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

在评论中(在你的回答下),@BLUEPIXY 指出因为 j 永远不会等于 lengthucontents 永远不会在 if(j == length)块。

因此,尽管您的代码示例(在 answer 部分中)看起来对您有效,但代码最终会失败。 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] = '[=10=]';
        break;
      }*/
      j++;//this increment ensures j is positioned 
          //correctly for NULL termination when loop exits
    }
  }
  ucontents[j]=NULL;//add NULL at end of loop
}