笔记
作业
定义自己的命名空间my_sapce,在my_sapce中定义string类型的变量s1,再定义一个函数完成对字符串的逆置。
法1:(直接把字符串传过去)
#include <iostream>
#include <cstring>
using namespace std;
namespace my_space {
string s1;
void swap(char &a,char &b);
void reverse(string &s1,int len);
}
using namespace my_space;
int main()
{
getline(cin,s1);
reverse(s1,s1.size());
cout << s1 << endl;
return 0;
}
void my_space::swap(char &a,char &b)
{
char temp=a;
a=b;
b=temp;
}
void my_space::reverse(string &s1,int len)
{
char *p=(char*)s1.c_str();
for(int i=0;i<len/2;i++)
{
swap(*(p+i),*(p+len-1-i));
}
}
法2:(先让char型的指针指向字符串的空间,再把char型的指针传过去)
#include <iostream>
#include <cstring>
using namespace std;
namespace my_space {
string s1;
void swap(char &a,char &b);
void reverse(char *p,int len);
}
using namespace my_space;
int main()
{
getline(cin,s1);
char *p=(char*)s1.c_str();
reverse(p,s1.size());
cout << s1 << endl;
return 0;
}
void my_space::swap(char &a,char &b)
{
char temp=a;
a=b;
b=temp;
}
void my_space::reverse(char *p,int len)
{
for(int i=0;i<len/2;i++)
{
swap(*(p+i),*(p+(len-1-i)));
}
}