返回顶部

收藏

编程实现字符串中单词的反转

更多

编程实现字符串中单词的反转,假设所有的单词均有空格分隔且标点符号当做字母处理。例如字符串“Who are you girl?”反转后为“girl? you are Who”.

#include <iostream>
#include <stack>
#include <vector>
#include <deque>
using namespace std;

//利用堆栈实现反转
char *reverseByStack(char *string)
{
    stack<char> sent;
    char *addr,*p;
    addr=p=string;

    while (*p!='\\0')
        sent.push(*p++); //push sentence into stack;

    while (true)
    {
        bool end=false;
        stack<char> word;
        while (sent.top()!=' ')
        {
            word.push(sent.top());
            sent.pop();

            if (sent.empty())
            {
                end=true;
                break;
            }
        }

        if (word.empty())
        {
            *string++=' ';
            sent.pop();
            if (sent.empty())
                break;
            continue;
        }
        else
        {
            while(!word.empty())
            {
                *string++=word.top();
                word.pop();
            }
            if (end)
                break;
        }
    }
    return addr;
}

void swap(char *s,char *e)
{
    while(s<e)
    {
        char temp=*s;
        *s=*e;
        *e=temp;
        s++;
        e--;
    }
}

//利用普通方法实现反转
char *reverseString(char *string)
{
    char *beg = string;
    char *end = beg+strlen(string)-1;

    //1.total reverse
    swap(beg,end);

    //2.word reverse
    while (*beg!='\\0')
    {
        if (*beg==' ')
        {
            beg++;
            continue;
        }
        end=beg;
        while(*end!=' '&&*end!='\\0')
            end++;
        swap(beg,--end);
        beg=++end;
    }
    return string;
}

int main()
{
    char string[25]="Who are you  girl?";
    char string2[25]="Who are you  girl?";
    cout<<"Before Reverse:"<<endl;
    cout<<string<<endl;

    cout<<"After (common method) Reverse:"<<endl;
    cout<<reverseString(string)<<endl;

    cout<<"After (stack method) Reverse:"<<endl;
    cout<<reverseByStack(string2)<<endl;
    return 0;
}
//该片段来自于http://outofmemory.cn

标签:c++,基础

收藏

0人收藏

支持

0

反对

0

»更多 您可能感兴趣的代码
  1. 2012-11-05 21:59:42java获得随机数代码 by 怪兽狂殴奥特曼
  2. 2014-05-09 17:00:27简单模拟股票和彩票 by lucasli
  3. 2014-05-10 19:02:38看不懂VS2008平台下的错误列表给出的提示信息 by 千万不要郁闷
  4. 2014-05-12 17:09:22生产者与消费者模型 by 蟋蟀哥
  5. 2014-05-17 20:06:25字符串染色问题 by Kevin.
  6. 2014-05-18 15:56:40Linux SLIST 使用 by qqmmcc
  7. 2014-05-19 20:07:13lockfree编程 by 童学芬
  8. 2014-05-21 15:50:02统计运行时间 by 跳跳虎
  9. 2014-05-21 19:27:38数组指针和指针数组 by aiheng1988
  10. 2014-05-22 16:49:06检出和分离c语言源程序错误的方法 by 跳跳虎
  11. 2014-05-22 21:07:53c语言的trim by 童学芬

发表评论