alg: 反转字符串中的单词顺序

#include <stdio.h>

//2. 反转字符串或反转段落中的单词顺序;
void reverse(const char *s,        //source string
                int n,            //length of s
                char *d)        //destination
{
    int i=n-1;
    int di=0;
    while(i>=0)
    {
        //find a word
        int si=i;
        for(; si>=0; i--)
        {
            if(s[si]==' ') break;
        }

        //copy to d
        for(int j=si; j<=i; j++)
            d[di++]=s[j];
        d[di++]=' ';
    }
}

int main(int argc, char *argv[])
{
    char *s = ("Hello, world\n");
    char d[100];

    reverse(s, strlen(s), d);

    return 0;
}

posted on 2011-02-17 14:04  cutepig  阅读(310)  评论(0编辑  收藏  举报

导航