编写一个单词反转,字符不反转的函数。

来源:互联网 发布:制作七字藏头诗的软件 编辑:程序博客网 时间:2024/05/18 01:52
如题:规则如下

输入:im a bad student

输出:student bad a im

方法1:不借助辅助的空间

#include <iostream>#include <algorithm>using namespace std;void ReverseWord(char a[], int begin, int end){for(; begin < end; ++begin, --end)swap(a[begin], a[end - 1]);}void Reverse(char str[]){int front = 0; int cur = 0;for(; str[cur] != '\0'; ++cur)if(str[cur] == ' '){ReverseWord(str, front, cur);front = cur + 1;}ReverseWord(str, front, cur);}int main(){//char s[] = "im a bad boy";char s[] = "im a bad student";int len = strlen(s);ReverseWord(s, 0, len);Reverse(s);cout<< s <<endl;return 0;}

方法1:借助辅助的空间

#include <iostream>#include <stack>#include <string.h>#include <algorithm>using namespace std;void PushStack(char s[], stack<string> &stk){const char *tag = " ";char *p = strtok(s, tag);while(p){stk.push(p);p = strtok(NULL, tag);}}int main(){stack<string> stk;char s[] = "im a bad student";PushStack(s, stk);//输出while(!stk.empty()){cout<< stk.top() << " ";stk.pop();}return 0;}


0 0
原创粉丝点击