用string类包含头文件**< string >
1, 初始化:
~~string s1(“he”);
~~ string m = “march”;
~~ string s2(2,‘x’ ); //2个x
可以把字符串赋值给string对象
~~ string s;
~~ s = ‘n’ ;
string对象长度用length()读取
string支持流读取运算符
~~ string str;
~~ cin>> str;
string 支持getline函数
~~ string s;
~~ getline(cin,s);
2, 赋值和连接
1:用=赋值
2: 用assign函数复制
3:用assign成员函数部分复制
~~ string s1(“catpig”), s2;
~~ s3.assign(s1, 1, 3); //从s1下标为1的字符开始复制3个字符
4:逐个访问string对象字符:
~~string s(“he”);
~~for(int i=0; i< s.length(); i++)
cout<< s.at(i) <<endl; //at会做范围检查
5:用+连接
6:函数append连接
~~ s2.append(s1,3,s1.size()); //下标3开始,s1.size()个字符,如果没有足够字符,则复制到最后一个字符
7: 函数substr
~~string s1(hello world"), s2;
~~ s2 = s1.substr(4,5); //下标4开始5个字符
3, 寻找string中的字符
1:函数find()
2: rfind 从后向前查找
3: 函数 find_first_of()
~~ s.find_first_of()(“abcd”); //从前向后找“abcd"中任何一个字符第一次出现的地方,找到返回字母位置。
4: 函数 find_last_of()
4, 插入string中的字符
1: insert()
~~ s.insert(5, s2);
~~ s1.insert(2, s2,5,3); //==把s2下标5开始3个字符插入s1下标2的位置
2: 函数 replace替换字符
~~ s.replace(2,3, “haha”,1,2);
3: ==c_str()==转换c语言式char*字符串
4: data()
5, 字符串流处理
#include< string>
#include< iostream>
#include< sstream>
字符串留处理:
- 字符串输入流istringstream
- 字符串输出流ostringstream
#include<bits/stdc++.h>
using namespace std;
main()
{
string input("Input test 123 4.7 A");
istringstream inputString(input);
string s1, s2;
int i;
double d;
char c;
inputString >> s1 >>s2>>i>>d >>c;
cout << s1<< endl<< s2<<endl;
cout << i<<endl << d<<endl<< c<< endl;
long L;
if(inputString >> L)
cout << "long\n";
else
cout <<"empty\n";
ostringstream outputString;
int a = 10;
outputString << "This "<<a<<" ok"<<endl;
cout<< outputString.str();
}
运行结果:
Input
test
123
4.7
A
empty
This 10 ok