【问题标题】:A C code to reverse a string反转字符串的 C 代码
【发布时间】:2015-04-25 17:19:15
【问题描述】:

有人看到这里的错误吗?我有其他解决方案。

int main()
{

  char line[100], res[100], temp[20];
  fgets( line, 100*sizeof(char), stdin);    
  int i, j, l;
  for( i=strlen(line)-1; i>=0; i--)
  {
    if(line[i]==' ')
        for(j=i+1, l=0; line[j]!=' ' && line[j]!='\0'; l++, j++)
            temp[l]=line[j];
    temp[++l]=' ';
    temp[++l]='\0';
    strcat(res, temp);
  }
  puts(res);
  return 0;
}

【问题讨论】:

  • 请告诉我们您实际看到的行为以及它与预期行为有何不同。
  • 永远不要这样做for( i=strlen(line)-1; i>=0; i--),你正在计算字符串的长度length的字符串次数,你应该知道strlen()循环遍历字符来计算它们。
  • strcat(res, temp); - 这不好。您永远不会将res[] 设置为终止缓冲区,而strcat 期望它是这样。所以寻找一个0 字符,如果你(不)幸运,你会找到一个有足够空间来实际连接你的源字符串的字符。

标签: c string debugging reverse


【解决方案1】:

l 和 j 仅在 line[i]==' ' 时初始化。

Witch 不会是第一次迭代的情况,其中 line[i] 将是 '\n'

【讨论】:

    【解决方案2】:

    for 和 if 循环不是必需的。由于数组遵循基于 0 的索引,i 的值应该从 0 到 strlen(line)-1,所以 j=i+1 应该是 j=i(第 1 行)。字符串应该以空值结尾 - 第 2 行。此外,l 已经在 for loop 中递增,因此使用后递增(或根本不使用它)代替前置递增(或根本不使用它)(第 3 行)。

    #include<stdio.h>
    #include<string.h>
    int main()
    {
    
     char line[100], res[100], temp[20];
     fgets( line, 100*sizeof(char), stdin);
     int i, j, l=0;
     res[0]='\0';   //line 2
     i=strlen(line)-1;
    
        for(j=i, l=0; line[j]!=' ' && line[j]!='\0'; l++, j--) //line 1
            {temp[l]=line[j];
             }
       temp[l++]=' ';   //line 3 (or temp[l]=' ')
       temp[l++]='\0';
    
       strcat(res, temp);
    
      puts(res);
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-30
      • 2011-07-01
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 2019-05-18
      • 2020-02-07
      相关资源
      最近更新 更多