字符数组(char ch[]):
#include<bits/stdc++.h>
using namespace std;
int main(){
//定义s[10],最多只能存4个字符,因为s[10]='\0'
char s[10]; //s[0],s[1],s[2]...s[9],'\0'
scanf("%s",s); //可改为:scanf("%s",s+n); 这样做输入:s[n]~s[10]
int len=strlen(s); //长度函数
printf("len=%d\n",len); //长度
for(int i=0;i<len;i++){ //输出
printf("%c ",s[i]);
}
return 0;
}
字符串(string):
#include<bits/stdc++.h>
using namespace std;
int main(){
string s="";
s+='a'; //加在结尾
s+="bcde"; //加在结尾
cout<<s<<endl;
cout<<"len="<<s.length()<<endl; //s.length相当于s.size()
return 0;
}
注意点:
1. 数据量比较大的时候用scanf, printf, 对应char数组
2. 数据量不大可以用cin, cout对应string类
find
#include<bits/stdc++.h>
using namespace std;
int main(){
string s="abcdef";
int pos=s.find('abc'); //找到返回位置,找不到返回-1
cout<<pos<<endl;
return 0;
}
substr
#include<bits/stdc++.h>
using namespace std;
int main(){
string s="abcdef";
cout<<s.substr(a,b)<<endl; //标识子串 从s[a]开始,往后的b个输出
cout<<s.substr(a)<<endl; //等同于“cout<<s.substr(a,s.size())<<endl;”
return 0;
}
字典序
查找
#include<bits/stdc++.h>
using namespace std;
int main(){
string s="abcdef";
string t="abcef";
int flag=(s<t); //-1,0,1
cout<<flag<<endl;
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main(){
string s="alojhoapbcvkkookokqodkowdfirvvejwjjcjeifhncasxxzxf";
int pos=s.find_first_of("aeiou"); //返回第一个出现的位置
//同时,还有:s.find_last_of("");
//int pos=s.find_last_of("aeiou");//返回最后个出现的位置
cout<<pos<<endl;
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main(){
string s="alojhoapbcvkkookokqodkowdfirvvejwjjcjeifhncasxxzxf";
int pos=s.find_first_of("aeiou"); //返回第一个出现的位置
while(1){ //不断把找到的“aeiou”变为‘r’
s[pos]='r';
pos=s.find_first_of("aeiou");
if(pos==-1) break;
}
cout<<s<<endl;
return 0;
}
更多关于字符串的函数,可咨询:www.cplusplus.com, 本人大力推荐
加微信群免费答疑,分享资料: