【问题标题】:Reversing a string in C using loop [duplicate]使用循环在C中反转字符串[重复]
【发布时间】:2017-02-23 20:20:01
【问题描述】:

这里是初级程序员。我正在尝试从用户那里获取输入,将其反转并显示结果。出于某种原因,它打印的是空白而不是反转的字符串。我知道array[i] 有正确的信息,因为如果我在for (int i=0; i<count; i++) 线上使用这个循环,它会打印正确的字符。它只是没有反向打印。我在这里没有得到什么?

#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(void)
{
    printf("Please enter a word: ");
    char *word = get_string();

    int count = strlen(word);

    char array[count];

    for (int i=0; i< count; i++)
    {
        array[i] = word[i];
    }

    for (int i=count-1; i==0; i--)
    {
        printf("%c ", array[i]);
    }
    printf("\n");
}

【问题讨论】:

  • 你的条件不对。应该是:for (int i=count-1; i&gt;=0; i--)
  • 在其他地方逐字复制输入有什么意义?为什么不直接从原处打印呢?
  • 如果你想反转字符串,你的第一个 for 循环必须改变。一个数组向上计数,另一个数组向下计数
  • @P.P.谢谢,我不知道为什么我没有想到。
  • @DavidSchwartz 一开始我在一个数组中完成了所有操作,将其分解以更好地调试它。

标签: c cs50


【解决方案1】:
for (int i=0; i< count; i++)
{
    array[i] = word[i];
}

你遍历字符串并复制它,你不要反转它。

在您的array 声明中还有一个等待中的细微错误,因为您没有为'\0' 字符终止符留出空间。将缓冲区作为 C 字符串传递给 printf,而不是逐个字符地传递将具有未定义的行为。

所以要修复这两个特定的错误:

char array[count + 1];
array[count] = '\0';

for (int i = 0; i< count; i++)
{
    array[i] = word[count - i];
}

附带说明,在这个小练习中使用 VLA 可能意义不大,但对于较大的输入,它很可能会溢出调用堆栈。小心。

【讨论】:

  • 你忘记了空终止字符(并且缓冲区太短了 1)
  • @Jean-FrançoisFabre - 是吗?如果这就是你投反对票的原因,那么你真的很高兴
  • @Jean-FrançoisFabre 他没有使用终止字符,而且他的缓冲区不是太短。缓冲区保存长度已知的字符,而不是 C 样式的字符串。无需分配额外的字节。
  • @Jean-FrançoisFabre - 很容易犯错误,在 15 秒后你的评论被否决了。道歉。
  • @Jean-FrançoisFabre - 这有点像鸡和蛋。我通常会在迭代中改进,直到我满意为止。但我无法证明不是 DV 让我这么做了。无论如何,DV 仍然存在的事实强烈表明它不是真实的 DV。
【解决方案2】:
// the header where strlen is
#include <string.h>

/**
 * \brief reverse the string pointed by str
**/
void reverseString(char* str) {
    int len = strlen(str);
    // the pointer for the left and right character
    char* pl = str;
    char* pr = str+len-1;
    // iterate to the middle of the string from left and right (len>>1 == len/2)
    for(int i = len>>1; i; --i, ++pl, --pr) {
        // swap the left and right character
        char l = *pl;
        *pl = *pr;
        *pr = l;
    };
};

然后调用函数:

int main(void) {
    printf("Please enter a word: ");
    char *word = get_string();

    // Just call the function. Note: the memory is changed, if you want to have the original and the reversed just use a buffer and copy it with srcpy before the call
    reverseString(word)
    printf("%s\n", word);
};

然后改变

char array[count];

for (int i=0; i< count; i++)
{
    array[i] = word[i];
}

// add an other byte for the null-terminating character!!!
char array[count+1];
strcpy(array, word);

【讨论】:

  • 没有任何解释的代码不会有一点帮助。您应该在使用时发布汇编代码。
  • 好的,但是有大量的代码 sn-ps 可以在 SO 上执行此操作(按照我的重复链接)。 OP 想知道 他的 代码中的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多