string 全新详解 (^0^)
一. string 初始化
string a="123"; 对
string a=123; 错
string a='a' 错
string a("qq") 对
string a(8) 错总而言之 string 在初始化的时候只能将字符串初始化给string变量;
但是可以将字符赋给string变量
如:string s;
s='n';
另外还有一种初始化方式:
string s(8,'x'); //将8个x初始化给s;
二.输入和赋值
输入:
给 string 输入方式有两种 :
string s;
1. cin >>s;
2 getline(cin ,s) 接受除了回车以外的任何字符,回车符在输入流中清空,不会留给下一个字符串;
赋值:
1. 用=赋值
string s1("hello"),s2;
s2=s1;2.用assign 成员函数赋值
string s1("hello"),s2;
s2.assign(s1);用assign成员函数部分的赋值
string s1("hello"),s2;
s2.assign(s1,1,3); //从s1的下标为1的字符开始( 包括下标为1的字符 )向后选择3的字符赋值给 s2
3. string s1("hello"),s2;
s2.assign(s1);
s2[1]='a'; //单个赋值//逐个访问string对象中的字符
4. for(int i=0;i<s1.length()+1;i++)
cout<<s1.at(i)<<endl; //成员函数at 会做范围检查,如果超出范围会抛出 out of range
//而下标运算符[]不做范围检查,但是at要慢一些
三.成员函数1. 字符串连接
string s1("hello"),s2("llll");
1.用 + 号s2+=s1;
2.用成员函数 append 连接
s1.append(s2); //把s2连接到s1后边 结果 hellollll另外 append 也可以选择性的连接
s1.append(s2,1,s2.size()); //从 s2的下标为1的字符开始( 包括下标为1的字符 )向后选择s2的字符;没有足够的字符, 直到s2的最后;
string s("hello")
cout << s.length() << endl;//length()获取长度;5
2.比较函数 compare
string s1("hello"),s2("hell");
int f=s1.compare(s2); hello>hell (以s1为主体比较)大于返回返回1 小于返回-1 等于返回0
也可部分比较
string s1("hello"),s2("hello");
int f=s1.compare(1,3,s2,0,3); -1-----e<h
4.substr 子串
string s1("he llo"),s2("hello"),s3("hell");
s2=s1.substr(1,3); -----> e l//substr #include <iostream> #include <string> using namespace std; int main () { string str="We think in generalities, but we live in details."; string str2 = str.substr (3,5); // "think" size_t pos = str.find("live"); // position of "live" in str string str3 = str.substr (pos); // get from "live" to the end cout << str2 <<endl; cout << str3 <<endl; return 0; } //结果:think // live in details.
5. swap;string s1("he llo"),s2("hello"),s3("hell");
s1.swap(s2);
6.查找6.1 find 从前向后找
string s1("helllo"),s2("hello"),s3("hell");
cout << s1.find("ll")<<endl;
从前向后查找“ll” 第一次出现的位置,如果找到,返回l的下标,如果找不到反回4294967295(系统默认书数)6.2 rfind 从后向前找
string s1("helllo"),s2("hello"),s3("hell");
cout << s1.find("ll")<<endl;
从后向前查找“ll” 第一次出现的位置,如果找到,返回l的下标,如果找不到反回4294967295(系统默认书数)
两者也可以指定在哪开始的位置
cout <<s1.find("ll",1);6.3 find_first_of()
string s1("hellloab");
cout <<s1.find_first_of("abcd")<<endl; abcd字符中任意一个字符从前向后查找第一次出现的位置 6
cout <<s1.find_last_of("abcd")<<endl; abcd字符中任意一个字符从后向前第一次出现的位置
cout <<s1.find_first_not_of("abcd")<<endl;不在abcd字符中任意一个字符从前向后第一次出现的位置
cout <<s1.find_last_not_of("abcd"); 不在abcd字符中任意一个字符从后向前第一次出现的位置
7.删除 //erase
string s1("123456789");
s1.erase(5);//把下标为5及5之后的字符删掉;结果12345
string s1("hello world");
s1.erase(5,1);//把下标为5及5之后的1个字符删掉; 结果 :helloworld
8. 替换 //replacestring s1("qwerty);
s1.replace(1,2,"1234567",1,4);//从第m个位置开始,替换n个字符; 结果 q2345rty
s1.replace(s1.find("e"),1,"1"); //与find 结合
cout << s1 << endl;9. 插入//insert 插入
string s1("hello world"),s2("123456");
s1.insert(5,s2,1,2);//把s2中的第1到第2的字符插入到s1中的第5个位置(空格不删去) 结果hello23 world
cout << s1 << endl;
附加内容:
string 类 可以直接比较字符大小
int main ()
{
string a,b;
cin >>a>>b;
if(a>b)
cout <<1;
else
cout <<2;
return 0;
}