1. 回文字符串
reverse 函数实现的是字符串的原地反转
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
string s;
while(cin>>s)
{
string a = s;
reverse(s.begin(),s.end());
if(s==a)
cout<<"Yes!"<<endl;
else
cout<<"No!"<<endl;
}
}
2. 不借用任何字符串库函数实现无冗余地接受两个字符串,然后把它们无冗余的连接起来。
如果是输入一串字符串并保存到字符数组中,系统会自动在后面补\0,无需自己输入。
#include <iostream>
using namespace std;
int main()
{
char a[101];
char b[101]; //字符数组,最后通常为\0,以表征字符串的结束
while(cin>>a>>b)
{
char res[201];
char *p=a; //指向字符数组的指针,直接赋值即可
int i=0;
while(*p!='\0')
{
res[i]=*p;
p++;
i++;
}
char *q=b;
while(*q!='\0')
{
res[i]=*q;
q++;
i++;
}
res[i]='\0';
cout<<res<<endl;
}
return 0;
}
3. C中也有一系列处理字符串的函数,在cstring头文件中,字符串处理缓存有:字符串拼接函数strcat(string 1,string 2)将字符串2接到字符串1的后面,字符串1的\0结束标志被删除;字符串拷贝strcpy(string 1, string 2)将字符串2复制到字符串1中;字符串比较函数strcmp(string 1,string 2),比较字符串大小关系;字符串长度函数strlen(s)。
4. 字符串内排序
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(char a, char b)
{
return a<b;
}
int main()
{
string s;
while(cin>>s)
{
sort(s.begin(),s.end(),cmp); // C++中的快速排序,可以直接调用,可以利用cmp实现多种功能
cout<<s<<endl;
}
}