方法一:在命名空间中定义一个函数
定义一个命名空间Myspace,包含以下函数:将一个字符串中的所有单词进行反转,并输出反转后的结果。例如,输入字符串为"Hello World",输出结果为"olleH dlroW",并在主函数内测试该函数。
#include <iostream>
using namespace std;
namespace Myspace {
void turn(string *s); //函数声明
}
void Myspace::turn(string *s) //
{
int len = (*s).length(); //s->length();
char temp; //中间变量
int i=0,j=0,k=0; //j用于保存开始位置,k用于保存单词结束的位置
while(i<len) //控制循环到字符串的最后一个位置
{
//找单词的结束位置
if(i==len-1||s->at(i)!=' '&&s->at(i+1)==' ')
{
k=i; //k应该为o的下标
}
//找单词的起始位置
if(i<len-1&&s->at(i+1)!=' '&&s->at(i)==' ') //i+1的位置不是空格,但是i的位置是空格
{
j = i+1; //j会停留在w的下标
}
while(j<k) //起始位置在结束位置前
{
temp = s->at(j);
s->at(j) = s->at(k);
s->at(k) = temp;
j++;
k--;
}
i++; //循环变量自增
}
}
int main()
{
string str = "Hello World";
Myspace::turn(&str);
cout << str << endl;
return 0;
}
方法二:使用函数
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
string str;
getline(cin,str); //从终端获取字符串
reverse(str.begin(),str.end());
cout << str << endl;
return 0;
}