1.2 单词翻转

//输入I am a student.输出student a am I.

#include <iostream>
using namespace std;
void reverse (char *s, int m, int n)//m,n 起点,终点
{
    //前后翻转
    for(int i=m-1,j=n-1;i<j;i++,j--)
    {
        char t= s[i];
        s[i]=s[j];
        s[j]=t;
    }
}

void reversestring (char*s, int n)
{
    reverse(s,1,n);
    cout<<s<<endl;
    int num=0;
    for (int i=0;i<n;i++)
    {
       if (s[i]=='\0' || s[i]==' ')
       {  
           reverse(s,i-num+1,i);
           num=0; //遇到空格后计数清零
       }
       else
           num=num+1;
    }
}

void main()
{
    char str[]="I am a student.";  
    int n= strlen(str); //长度为8 sizeof需要加1
    reversestring(str,n);
    cout<<str<<endl;
    system("pause");
}
相关文章
相关标签/搜索