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

前端 未结 30 1923
长发绾君心
长发绾君心 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:38

    #include 
    #include 
    #include 
    
    void strrev(char *str)
    {
            if( str == NULL )
                    return;
    
            char *end_ptr = &str[strlen(str) - 1];
            char temp;
            while( end_ptr > str )
            {
                    temp = *str;
                    *str++ = *end_ptr;
                    *end_ptr-- = temp;
            }
    }
    
    int main(int argc, char *argv[])
    {
            char buffer[32];
    
            strcpy(buffer, "testing");
            strrev(buffer);
            printf("%s\n", buffer);
    
            strcpy(buffer, "a");
            strrev(buffer);
            printf("%s\n", buffer);
    
            strcpy(buffer, "abc");
            strrev(buffer);
            printf("%s\n", buffer);
    
            strcpy(buffer, "");
            strrev(buffer);
            printf("%s\n", buffer);
    
            strrev(NULL);
    
            return 0;
    }
    

    This code produces this output:

    gnitset
    a
    cba
    

提交回复
热议问题