您的位置:首页 > 编程语言 > C语言/C++

将一句话中的单词进行倒置c++代码实例及运行结果

2018-02-05 16:59 190 查看
需要进行两次倒置,具体看代码解释

c++代码

#include <iostream>
#include<string.h>
using namespace std;

int main()
{
char *str="My Name is XiaoMing";
cout<<"源字符串为"<<str<<endl;
char strInv[30]={};//存放转置后的程序,char *strInv出错
int len;
len=strlen(str)-1;
int i=0;
//第一次转置
while(len!=-1)
{
strInv[i++]=str[len--];
}
cout<<"第一次转置后字符串为"<<strInv<<endl;
//第二次转置
i=0;
int begin,end,temp;
while(strInv[i])
{

if(strInv[i]!=' ')
{
begin=i;
while(strInv[i]&&strInv[i]!=' ')
i++;
end=i-1;
}

while(end>begin)
{
temp=strInv[begin];
strInv[begin]=strInv[end];
strInv[end]=temp;
begin++;
end--;
}
i++;
}
cout<<"第二次转置后字符串为"<<strInv<<endl;

return 0;
}



运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: