使用循环在C中反转字符串

时间:2017-02-23 20:20:02

标签: c cs50

初学者程序员在这里。我正在尝试从用户那里获取输入,将其反转并显示结果。出于某种原因,它是打印空白而不是反转的字符串。我知道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");
}

2 个答案:

答案 0 :(得分: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 :(得分:0)

// 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);
相关问题