C++ 字符串翻转

1.student. a am I   ------>   I am a student

class Solution {
public:
    string ReverseSentence(string str) {
        int len = str.length();
        if(len==0) return "";
        int i = 0, j = 0;
        reversestr(str, 0, len - 1);//先翻转整个字符串
        
        while(i < len)
        {
            if(str[i] == ' ')
            {
                i++;
                j++;
            }
            else if(str[j] == ' ' || str[j] == '\0')//再逐个单词翻转
            {
                reversestr(str, i, j - 1);
                i = j;
            }
            else
            {
                j++;
            }
        }
        
        return str;
    }
    
    void reversestr(string &str, int start, int end)//写一个C++中reverse函数的实现
    {
        for(int i = start; i < end; i++)
        {
            char tmp = str[i];
            str[i] = str[end];
            str[end] = tmp;
            end--;
        }
    }
};

 

你可能感兴趣的:(C++ 字符串翻转)