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

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

    With C++ lambda:

     auto reverse = [](std::string& s) -> std::string {
            size_t start = 0, end = s.length() -1;
            char temp;
    
            while (start < end) {
              temp = s[start];
              s[start++] = s[end];
              s[end--] = temp;
            } 
    
            return s;
       };
    

提交回复
热议问题