Invert string in C - String problem with even number of characters

Asked

Viewed 83 times

0

Well, I have the code below that should reverse a string and show if it is a palindrome. However, when the word has an even number of characters the result is wrong. I think the error is in the third for, can anyone see any problem? Below is an example of the output with the palindrome "that".

#include <stdio.h>
#include <string.h>
#define SIZE 21

int main (){
    char palavra[SIZE];
    int last;
    printf("Digite a palavra: ");
    scanf("%s", palavra);

    for (int i = 0; palavra[i] != 0; ++i) { // determina o fim da string
        last = i + 1;
    }

    char palavraReduzida[last], palavraInvertida[last]; // cria duas strings, uma com seu tamanho real e outra que vai ser invertida

    for(int i = 0; i <= last; ++i){
        palavraReduzida[i] = palavra[i]; //adiciona os caracteres a string de tamanho real
    }
    for(int i = 0; palavraReduzida[i] != 0; ++i) {
        palavraInvertida[i] = palavraReduzida[last - 1]; // Inverte a string
        --last;
    }

    printf("%s %d %s %d\n", palavraReduzida, sizeof(palavraReduzida), palavraInvertida, sizeof(palavraInvertida)); //Escreve a string invertida e a string de tamanho
    if(strcmp(palavraReduzida, palavraInvertida) == 0)       //Compara as strings                                  //Também mostra os tamanhos
        printf("E um palindromo");
    else
        printf("Nao e um palindromo");
    return 0;
}

inserir a descrição da imagem aqui

  • And you have to do it all for some reason or you can do it simpler. https://answall.com/q/192842/101

  • True, it helped a lot, thank you! But anyway, you would know why at the end of the inverted string appear this unexpected character?

  • 1

    Why you failed to add the ending character ' 0'.

  • Good evening! Why not use the strrev() function to invert your string? It is inside the string library.h... It would make your resolution much easier.

1 answer

1


You’re not putting the ' 0' at the end of wordInvertida.

add the following line before the third row is:

palavraInvertida[last] = '\0';

Browser other questions tagged

You are not signed in. Login or sign up in order to post.