如何用C++实现单词字母顺序的反转:例如:将Hello world!变为:olleH dlrow!

如题所述

#include <stdio.h>
#include <string.h>
#define N 100

//设置全局变量 一般 倒转 这种 最好用堆栈 来做 因为是先进后出 先把前面的字母放进去 然后最好弹出最先放出的字母
char stack[N];
int top=-1;

void push(char ch)
{
stack[++top]=ch;
}

int pop(void)
{
return stack[top--];
}

int main ()
{
char Input[]="Hello World! good ";
int length,i;
int j=-1;
length = strlen(Input);
printf("length is %d",length);
// char temple[length+1]; // strlen (Input)得到的是 除了 字符串结束符的 字符个数 所以要加上1
for(i=0;i<length+1;i++)
{
if((Input[i]==' ')||i==length) //假设空格 来区分单词 It's 算一个单词
{
while(top!=-1)
{
j++;
Input[j]=pop();

}
j++;
}

else
push(Input[i]);
}
printf("\n");
printf("%s",Input);
getchar();
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-04-01
#include <iostream>
#include <string.h>
#include <conio.h>
using namespace std;
int main ()
{
int i,j,k;
char ch[1000000],c;
gets(ch);
for (j=0;ch[j]!='\0';j++)
{
for(i=j;ch[i]!=','&&ch[i]!=' '&&ch[i]!='.'&&ch[i]!='\0';i++)
{}
for(k=0;k<(i-j)/2;k++)
{
c=ch[j+k];
ch[j+k]=ch[i-1-k];
ch[i-1-k]=c;
}
j=i;
}
puts(ch);
getch();
return 0;
}
这个可是一个万能的,关键在于判断,不论你输入什么都可以得到那样的结果!
第2个回答  推荐于2016-09-30
#include <stdexcept>
#include <iostream>
#include <string>
using namespace std;

char *rev_str( char *in_str )
{
int i;
char ch=0;
int len=strlen(in_str);
for (i=0;i<len/2;i++ )
{
ch=in_str[i];
in_str[i] = in_str[len-i-1];
in_str[len-i-1] = ch ;
}
return in_str ;
}

int main()
{
char str[128],*p=str;
char one_word[32];
strcpy( str , "Hello world !" );
while( *p )
{
while( *p == ' ' )
{
cout <<*p ;
p++;
}
sscanf(p,"%s",one_word);
rev_str( one_word );
cout << one_word ;
p+=strlen(one_word);
}
cout << endl ;
getchar();
return 0;
}追问

朋友能给我讲一讲吗?本人是C++新手什么都不会啊!能给加上注释吗

追答

你哪里看不懂啊,你先将迷惑的地方加上提示,我方便给你加注释,呵呵,不然我没有针对性,不好加

本回答被提问者采纳
第3个回答  2011-09-17
如果你学过栈的用法,可以用栈来实现。具体怎么做我要做还得用不少时间,所以你自己看看书就可以喽
相似回答