码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse words in a string

时间:2015-02-12 21:28:31      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:



技术分享

刚看到这个题目,手痒了.还挺有意思的...
#include <stdio.h>

int main()
{

    char str[] = "Please reverse this string!";

    printf("%s\n", str);

    str_rev(str);

    printf("%s\n", str);

    return 0;
}

int str_rev(char *string)
{
    if(!string)
    {
        return 0;
    }

    int ins_pos = 0;
    int ch = 0;
    int swap_time = 0;

    int i = 0;
    int j = 0;

    int counter = 0;
    int word    = 0;

    for(i = 0, word = 1; string[i] != ‘\0‘; i++)
    {
        if(string[i] == ‘ ‘)
        {
            word++;
        }
    }
    counter = i;

    for(j = 0, swap_time = 0, ins_pos = 0, ch = 0;
        j < word - 1;
        j++)
    {
        for(swap_time = 0; string[counter-1] != ‘ ‘;)
        {
            ch = string[counter-1];

            for(i = counter - 1; i > ins_pos; i--)
            {
                string[i] = string[i-1];
            }
            string[ins_pos] = ch;
            swap_time++;
        }

        ins_pos += swap_time;
        ch = string[counter-1];

        for(i = counter - 1; i > ins_pos; i--)
        {
        string[i] = string[i-1];
        }
        string[ins_pos] = ch;
        ins_pos++;
    }

    return 0;
}

技术分享




技术分享

Reverse words in a string

标签:

原文地址:http://blog.csdn.net/cinmyheart/article/details/43770541

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!