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

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

    My answer would be similar to most of them, but please find my code here.

    //Method signature to reverse string
    string reverseString(string str);
    
    int main(void){
        string str;
        getline(cin, str);
        str =  reverseString(str);
        cout << "The reveresed string is : " << str;
        return 0;
    }
    
    /// 
    ///     Reverses the input string.
    /// 
    /// 
    ///    This is the input string which needs to be reversed.
    /// 
    /// 
    ///     This method would return the reversed string
    /// 
    
    string reverseString(string str){
        int length = str.size()-1;
        char temp;
        for( int i=0 ;i<(length/2);i++)
        {
            temp = str[i];
            str[i] = str[length-i];
            str[length-i] = temp;
        }
        return str;
    }
    

提交回复
热议问题