Search code examples
cfor-loopprintfreversec-strings

Reversing a word in C and then storing that reversed word to use in a printf


So basically I'm trying to reverse a word (a single word, not a string with multiple words) and I've managed to reverse the word using this

{
    int end, x;
    end = strlen(myString) - 1;
    for (x = end; x >= 0; --x) {
        printf("%c", myString[x]);
    }
}

(myString is defined somewhere else in the code)

But here's the kicker, I need to print the reversed word like this:

printf("The word reversed is '%c'", myString);

And I've no idea how to actually take the word reversed by the for loop and putting it into the second printf command. Any ideas?


Solution

  • Here you are.

    for ( size_t i = 0, n = strlen( myString ); i < n / 2; i++ )
    {
        char c = myString[i];
        myString[i] = myString[n - i - 1];
        myString[n - i - 1] = c;
    }
    
    printf("The word reversed is '%s'\n", myString);