How do you reverse a string in place in C or C++?

前端 未结 30 1955
长发绾君心
长发绾君心 2020-11-22 00:37

How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?

30条回答
  •  面向向阳花
    2020-11-22 01:28

    If you don't need to store it, you can reduce the time spent like this:

    void showReverse(char s[], int length)
    {
        printf("Reversed String without storing is ");
        //could use another variable to test for length, keeping length whole.
        //assumes contiguous memory
        for (; length > 0; length--)
        {
            printf("%c", *(s+ length-1) );
        }
        printf("\n");
    }
    

提交回复
热议问题