【问题标题】:How to reverse a array of chars and then store the reversed array of char to another array?如何反转一个字符数组,然后将反转的字符数组存储到另一个数组?
【发布时间】:2015-07-07 06:32:39
【问题描述】:

我一直在研究这个非常简单的问题。我正在尝试反转一个字符数组,然后使用 c 语言将这个反转的字符数组存储到另一个数组中。这是我的代码,我无法弄清楚我的代码有什么问题。我真的不明白为什么当我尝试打印出我的 stcp 时,我的 stcp 是带有反转字符串的数组,屏幕上什么也没有显示。请提供建议,任何帮助将不胜感激。

#include<stdio.h>

int main() {
    char st[100];
    scanf("%s", st);
    int count = 0;
    while(st[count] != '\0'){
        count++;
    }

    //printf("%s", st);
    char stcp[100];
    int i, j = 0;
    for(i = count-1; i >= 0; i--){
        st[i] = stcp[j];
        j++;
    }

    puts(stcp);
    return 0;
}

【问题讨论】:

  • 如果是C,那么你不应该将你的问题标记为C++,因为在C++,你所要做的就是打电话给std::reverse
  • st[i] = stcp[j]; --> stcp[j] = st[i]; .. stcp[j] = 0;
  • 次要:使用size_t count 比使用int count stackoverflow.com/a/994357/2410359 更好

标签: c arrays string reverse


【解决方案1】:

我认为你的意思是以下

char stcp[100];
int i = count, j = 0;

while ( i != 0 ) stcp[j++] = st[--i];
stcp[j] = '\0';

至于你的原始代码,那么你必须在这个语句中交换操作数

   st[i] = stcp[j];

并且字符串stcp 必须附加终止零。

考虑到函数 main 应该像 C 一样定义

int main( void )

至于我,我将变量countij 声明为具有size_t 类型。

【讨论】:

    【解决方案2】:

    你需要切换这一行:

    st[i] = stcp[j];
    

    到这里:

    stcp[j] = st[i];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2021-08-23
      相关资源
      最近更新 更多