字符串单词反向输出程序

来源:互联网 发布:港澳直播软件 编辑:程序博客网 时间:2024/06/02 05:11

/* code by xusheng */

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

void Printword(char str[],int begin,int end)
{
    for(int i = begin;i<end;i++)
    {
        printf("%c",str[i]);
    }
}

void StrReverse(char str[])
{
    int len = strlen(str);
    int end = len;
    int begin = 0;
    for(int i =len-1;i>=0;i--)
    {
        if(str[i] == ' ')
        {
            begin = i+1;//begin是闭区间,所以要把空格弄掉
            Printword(str,begin,end);
            end = i;//end是开区间,所以可以等于空格位置
            printf("%c",' ');//除了不是最前面的单词打印,都需要附带输出个空格
        }
    }
    Printword(str,0,end);
}

int main()
{
    char str[] = "test ok myinfo china";
    StrReverse(str);

}