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

前端 未结 30 1953
长发绾君心
长发绾君心 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条回答
  •  梦毁少年i
    2020-11-22 01:14

    #include
    #include
    
    int main()
    {
        char *my_string = "THIS_IS_MY_STRING";
        char *rev_my_string = my_string;
    
        while (*++rev_my_string != '\0')
            ;
    
        while (rev_my_string-- != (my_string-1))
        {
            printf("%c", *rev_my_string);
        }
    
        getchar();
        return 0;
    }
    

    This is optimised code in the C language for reversing a string... And it is simple; just use a simple pointer to do the job...

提交回复
热议问题