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

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

    Here is the cleanest, safest, easiest way to reverse a string in C++ (in my opinion):

    #include 
    
    void swap(std::string& str, int index1, int index2) {
    
        char temp = str[index1];
        str[index1] = str[index2];
        str[index2] = temp;
    
    }
    
    void reverse(std::string& str) {
    
        for (int i = 0; i < str.size() / 2; i++)
            swap(str, i, str.size() - i - 1);
    
    }
    

    An alternative is to use std::swap, but I like defining my own functions - it's an interesting exercise and you don't need to include anything extra.

提交回复
热议问题