1字符数组输入
char buf[100];
fgets(buf,100,stdin);//可读取一整行元素,但包含换行符\n
2.字符串和字符数组转换
char buf[100];
scanf("%s",buf);
string str = buf;//将字符数组生成一个C++风格的字符串
printf("str=%s\n',str.c_str());//将C++风格的字符串转换为字符数组
3.字符串长度
string str;
str.size()//字符串长度,例:hello,size=5,length=5;
str.length();
4.访问每个字符
访问每个字符
string s;
cin>>s;
for(int i=0;i<s.size();i++){
printf("%c\n",s[i]);
}
string str;
cin>>str;
for(string::iterator it=str.begin();it!=str.end();it++){//采用迭代器
printf("%c\n",*it);
}
例:
char s[110];
cin.getline(s,110);
cout<<strlen(s)<<endl;
string a=s;
cout<<a.size()<<endl;
cout<<a.length();
输入:hello hello
输出为:
11
11
11
char s[110];
fgets(s,110,stdin);
cout<<strlen(s)<<endl;
string a=s;
cout<<a.size()<<endl;
cout<<a.length();
输入:hello hello
输出为:
12//因为包含最后的换行符
12
12
5.应用
连接:+
删除:s.erase()//删除从第几个位置之后的元素
清空:s.clear()
查找:s.find()
查找成功返回查找到的起始下标
查找失败返回string::npos
string a;
cin>>a;
a=a+"world";
cout<<a<<endl;
a.erase(7);
cout<<a<<endl;
int pos=a.find("are");
if(pos!=string::npos)
cout<<"Found,pos="<<pos<<endl;
else cout<<"Not Found!"<<endl;
pos=a.find("wo");
if(pos!=string::npos)
cout<<"Found,pos="<<pos<<endl;
else cout<<"Not Found!"<<endl;
输入:hello
输出:helloworld
hellowo
Not Found!
Found,pos=5