1.问题描述
例如输入“i love you”,则反转该字符串的结果应该是“you love i”,将该结果存入一个字符串中。
2.解决方法一:栈的思想,如图1所示。
a.分别将'i' "love" "you"压入栈中。
b.从栈顶取出字符串得到的结果刚好为"you" "love" "i"
c.实现代码如下:
/************************************************************************/
/*字符串反转,栈的方法 */
/************************************************************************/
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
#define OK 1
#define ERROR 0
#define MAX 20
typedef int Status;
typedef struct
{
string A[MAX];
int top;
}Sqstack;
Status Push(Sqstack *s,string &inStr)//入栈操作
{
if (MAX-1 == s->top)
return ERROR;
s->top++;
s->A[s->top] = inStr;
return OK;
}
Status Pop(Sqstack *s,string &outStr)//出栈操作
{
if (-1 == s->top)
return ERROR;
outStr = s->A[s->top];
s->top--;
return OK;
}
int main()
{
Sqstack stack1;
stack1.top = -1;
string strbuf = "";
char ch;
while (cin.get(ch))//将"i love you",压入栈中
{
if (ch == '\n')
{
Push(&stack1,strbuf);
break;
}
if (ch != ' ')
strbuf += ch;
else
{
Push(&stack1,strbuf);
strbuf = "";
}
}
char B[200];
memset(B,0,sizeof(B));
char *p = B;
int isTack = 1;
int len = 0;
strbuf = "";
char blank = ' ';
while(isTack)//从栈中取出字符串,存入字符数组B中
{
strcpy(p,strbuf.c_str());
len = strlen(strbuf.c_str());
p += len;
if (((stack1.top+1) != 0)&&(len != 0))
{
strcpy(p,&blank);
p++;
}
isTack = Pop(&stack1,strbuf);
}
printf(B);
return 0;
};
d.运行结果如下:
3.解决方法二:反转两次的思想,这个方法参照以前的思想,我做了加强,可以应对多个空格的情况,如" i love you "。
a.第一次反转得到"uoy evol i"
b.第二次局部反转得到"you love i"
/************************************************************************/
/*字符串反转,反转两次的方法 */
/************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void ReFirst(char *instr)//第一次反转将"i love you"反转为"uoy evol i"
{
int len = strlen(instr);
char *low; //指向字符串第一个位置
char *high; //指向字符串最后一个位置
low = instr;
high = low + len -1;
char ch;
while (low < high)
{
ch = *low;
*(low++) = *high;
*(high--) = ch;
}
}
void ReSec(char *low,char *high)//第二次反转为局部反转,例如"uoy"反转为"you"
{
char ch;
while (low < high)
{
ch = *low;
*(low++) = *high;
*(high--) = ch;
}
}
int main()
{
char input[] = " i love you ";
ReFirst(input);
char *p1 = input;
char *p2 = input;
while(p2++)
{
if (*p2 == '\0')//如果是末尾
{
ReSec(p1,p2-1);
break;
}
if(*p2 == ' '&&*p1 != ' ')//遇到空格
{
ReSec(p1,p2-1);
p1 = p2;
}
else if ((*p1 == ' ')) //忽略多余空格
{
p1 = p2;
}
}
printf(input);
printf("\n");
return 0;
};
c.运行结果如下: