STL

1.string容器

要包含头文件<string>

string对象的初始化

 

//c++中单引号表示字符型;双引号表示字符串类型 
string s1 (8,'x');  //表示8个x ,只能表示字符型,不能表示字符串类型 
string error1 (8,"x");
string month = "March"; 
string s2("March"); 
//只能对初始化字符串类型 ,字符和数字是不可以的 
string error2 ('x');
string error3 ('1');
//若改为字符串类型即可 
//或将字符类型复制给string对象也可以
string s;
s = 'n';

 

string对象的长度计算

cout<< s.size() << endl;
cout<< s.length() << endl;

string支持流读运算符和getline函数

string s;
cin >> s; //遇到空格 回车 Tab 停止
    
string ss;
getline(cin,ss);

string的赋值与链接

  • 用 = 赋值 
string s1("cat"),s2;
s2=s1;

用assign成员函数赋值 

tring s5("hernt"),s6;   
s6.assign(s5,4,3); //从下标为1(下标从0开始)开始3个字符赋值给s6,若超出长度则只到末尾 

单个字符的复制 

s2[5]=s1[3]='a';

逐个访问string对象的字符(两种方法)

for(int i=0;i<s1.length();i++){
     cout<< s1[i] << endl;
}    //不做范围检查,速度要快一点 

for(int i=0;i<s1.length();i++){
     cout<< s1.at(i) << endl;
    }    //成员函数at会做范围检查,若超出范围,会抛出out_of_range异常(暂时还没有学到) 

用+运算符连接字符串 

string s1("hello"),s2("world");
s1+=s2;

用成员函数 append 连接字符串

string s1("hello"),s2("world");
s1.append(s2);
s2.append(s1,3,s1.size( ));// 把s1从3开始的s1.size()个字符复制到s2中,若没有足够的,则复制到最后一个 
    

比较string

用关系运算符比较string的大小 

string s1("hello"),s2("hello"),s3("hell");
bool b=(s1==s2);
cout << b <<endl;
b=(s1==s3);
cout << b << endl;
b=(s1>s3);
cout << b << end

用成员函数compare比较string的大小

string s1("hello"),s2("hello"),s3("hell");
int f1 = s1.compare(s2);
int f2 = s1.compare(s3);
int f3 = s3.compare(s1);
int f4 = s1.compare(1,2,s3,0,3); //s1的从下标为1开始的两个字符和从s3下表为0开始的3个字符 
int f5 = s1.compare(0,s1.size(),s3);
//相同输出0;大于输出1;小于输出-1; 

成员函数

substr

 s2 = s1.substr(4,5) // 把s1从下标4开始的5个字符复制到s2 

swap

s1.swap.(s2)

find

string s1("hello world"),s2("lo");
s1.find(s2); //在s1中从前往后找s2第一次出现的地方,若找到,则返回s2的开始位置(即s2的第一个字符在s1所在位置的下标),如果不能,则返回string::npos(string中定义的静态常量)
s1.find(s2,1); //在s1中从第一个字符从前往后找s2第一次出现的地方
if(s1.find(s2) == string::npos)//判断

 

rfind

string s1("hello world"),s2("lo");
s1.rfind("lo"); //在s1中从后往前找s2第一次出现的地方,若找到,则返回s2的开始位置(即s2的第一个字符在s1所在位置的下标),如果不能,则返回string::npos(string中定义的静态常量)
if(s1.rfind("lo") == string::npos)//判断

 find_first_of()

s1.find_first_of(s2);// 在s1中从前向后查找字符串s2中任何一个字符第一次出现的地方,如果找到,返回找到字母的位置,若找不到,返回string::npos.

find_last_of()

s1.find_last_of("oeo");// 在s1中从前向后查找"oeo"中任何一个字符最后一次出现的地方,如果找到,返回找到字母的位置,若找不到,返回string::npos.

find_first_not_of()

s1.find_fist_not_of(s2) //在s1中从前往后找查不在s2中的字符第一次出现的地方,若找到,返回找到字符的位置,若找不到,返回string::npos

find_last_not_of()

s1.find_last_not_of(s2) //在s1中从后往前找查不在s2中的字符第一次出现的地方,若找到,返回找到字符的位置,若找不到,返回string::npos

erase()

s1.erase(5); //去掉下标5及之后的字符

replace

s1.replace(2,3,s2); //将s1中下标2开始的3个字符换成字符串s2
s1.replace(2,3,s2,1,2);//将s1下标为2开始的3个字符换成字符串s2下标为1开始的2个字符

insert()

s1.insert(5,s2); //将s2插入s1下标5的位置
s1.insert(2,s2,5,3); //将s2中下标5开始的3个字符插入s1下标2的位置

c_str()

printf("%s",s1.c_str()); // s1.c_str()返回传统的const char*类型字符串,且字符串以'\0'结尾,就可以用C语言的库函数了

data()

//返回一个char*类型的字符串

 

字符串流处理

输入流 istringstream

输出流 ostringstream

 

posted @ 2021-01-17 22:03  TXCCXT  阅读(77)  评论(0)    收藏  举报