1.在C语言中,一般使用字符数组 char str[]来存放字符串,但是使用字符数组有时会显得操作麻烦,而且容易因经验不足而产生一些错误。为了使编程者可以更方便地对字符串进行操作,在C++中引入 string 类型。
如果要使用string,需要添加string头文件,即 #include<string> (注意 string.h 和string 是不一样的头文件)。除此之外,还需要在头文件下面加上一句:“using namespace std;” 。
2. 如果要读入和输出整个字符串,则只能用 cin 和 cout ,具体解释和操作如下:
#include<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
//string str="ahgdfshgw";
string str;
cin>>str;
for(int i=0;i<str.length();i++)
{
cout<<str[i]<<endl;
}
cout<<str<<endl;
printf("%s\n",str.c_str());
//通过迭代器访问
for(string::iterator it=str.begin()+2;it!=str.end();it++)
{
printf("%c",*it);
}
cout<<endl;
string str1="hdsjdlk";
string str2="shjaks";
str1=str1+str2; //string的加法,可以讲两string直接拼接起来
cout<<str1<<endl;
//可以直接进行比较大小,比较规则是字典序
string str11="aa",str12="aaa",str3="abc",str4="xyz";
if(str11<str12) cout<<"ok1"<<endl;
if(str11!=str3) cout<<"ok2"<<endl;
if(str4>=str3) cout<<"ok3"<<endl;
//可以进行访问长度
cout<<str.length()<<endl;
//string 的 insert() 函数有多种写法这里给出两种写法:
string t1="abcxyz",t2="opq";
t1.insert(3,t2);
t1.insert(t1.begin()+3,t2.begin(),t2.end()); //在t1的3号位(即 c 和 x 之间)插入 t2;
t1.erase(t1.begin()+3); //单个删除
t1.erase(t1.begin()+2,t1.end()-1); //区间删除
t1.erase(3,2); //删除从3号位开始的2个字符
t1.clear(); //全部清除
string t3="Thank you for your smile.";
cout<<t3.substr(0,5)<<endl;
cout<<t3.substr(14,5)<<endl;
cout<<t3.substr(19,5)<<endl;
cout<<t1<<endl;
string t4="you";
string t5="me";
if(t3.find(t4) !=string::npos) // 从t4 是 t3 的子串时,返回其在 t4 中第一次出现的位置;如果 t4 不是 t3 的子串 ,那么返回 string::npos。
{
cout<<t3.find(t4)<<endl;
}
if(t3.find(t4,7)!=string::npos) // 从 t3 的 7 号位 开始匹配 t4 返回值与上相同
{
cout<<t3.find(t4,7)<<endl;
}
if(t3.find(t5)!=string::npos)
{
cout<<t3.find(t5)<<endl;
}
else
{
cout<<"I know there is no position for me."<<endl;
}
string s1="Maybe you will turn around.";
string s2="will not";
string s3="surely";
cout<<s1.replace(10,4,s2)<<endl; //把 s1 10号位开始,长度为 len 的子串 替换为 s2;
cout<<s1.replace(s1.begin(),s1.begin()+5,s3)<<endl; //把 s1 的迭代器[it1,it2)范围的子串替换为 s3
return 0;
}