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

Time:10-04

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?

CodePudding user response:

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);

CodePudding user response:

If the string you are passed is a literal instead of an allocated pointer, you'll need to make a reverse-copy of the string into an allocated buffer. Same applies if you are trying to avoid corrupting the orignial string.

// allocate a buffer big enough to hold a copy of the string
int len = strlen(myString);
char* reverse = malloc(len 1);

// reverse copy it over.
for (size_t i = 0; i < len; i  )
{
    reverse[i] = myString[len-1-i];
}
reverse[len] = '\0'; // null terminate our new string

printf("Reversed word: %s\n", reverse);

// free the string when you are done with it
free(reverse);
  • Related