i am a student.转为student. a am i

第一步:将 i am a student. 整体逆转为 .tneduts a ma i
第二步:以空格为界,部分逆转

// i am a student.  --> student. a am i
#include
#include
using namespace std; 
void Reverse(char *left, char *right)
{ 
    if (left == NULL || right == NULL)
        return;
    while (left < right)
    {
        swap(*left, *right);
        left++;
        right--;
    }
}
char *ReverseSentence(char* str)
{
    if (str == NULL)
        return NULL;
    int len = strlen(str);
    char *pBegin = str;
    char *pEnd = str+len-1;
    Reverse(pBegin, pEnd);
    pBegin = pEnd = str;
    while (*pBegin != '\0')
    {
        if (*pBegin == ' ')
        {
            pBegin++;
            pEnd++;
        }
        else if (*pEnd == ' ' || *pEnd == '\0')
        {
            Reverse(pBegin, --pEnd);
            pBegin = ++pEnd;
        }
        else
            pEnd++;
    }
    return str;
}
int main()
{
    char str[] = "i am a students";
    ReverseSentence(str);
    system("pause");
    return 0;
}

你可能感兴趣的:(数据结构)