【问题标题】:Add all characters except \r to new string将除 \r 之外的所有字符添加到新字符串
【发布时间】:2016-09-03 04:24:32
【问题描述】:

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

谢谢。

【问题讨论】:

  • ucontents[i] :使用其他索引变量代替i。和空终止符添加到结尾。
  • 谢谢。我已经按照您的建议在下面添加了我如何修复它。我是否正确添加了空终止符?

标签: c string c-strings chars


【解决方案1】:

在 cmets 中(根据您的回答),@BLUEPIXY 指出因为 j 永远不会等于 length,所以 ucontents 永远不会在 if(j == length) 块中以 NULL 结尾。

因此,尽管您的代码示例(在 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] = '\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
}

【讨论】:

  • 谢谢。我更改了代码以取出冗余块。
【解决方案2】:

这样固定。谢谢,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] = '\0';
        break;
      }
      j++;
    }
  }
}

【讨论】:

  • 谢谢。那比我做的要好。我正在将一个程序从 C++ 移植到 C。
  • @SamSaint-Pettersen - 你的if (j == length) 块永远不会被执行。 (这就是 BLUEPIXY 的评论所说的)
  • @ryyker:谢谢。我明白。我的意思是样本更好,因为它正确附加了空字符。
猜你喜欢
  • 2015-12-17
  • 1970-01-01
  • 2021-07-02
  • 2011-06-23
  • 1970-01-01
  • 1970-01-01
  • 2014-11-08
  • 2017-10-15
  • 1970-01-01
相关资源
最近更新 更多