string类本不是STL的容器,但是它与STL容器有着很多相似的操作,因此,把string放在这里一起进行介绍。 之所以抛弃char*的字符串而选用C++标准程序库中的string类,是因为他和前者比较起来,不必担心内存是否足够、字符串长度等等,而且作为一个类出现,他集成的操作函数足以完成我们大多数情况下的需要。我们尽可以把它看成是C++的基本数据类型。
string的头文件#include
#include <iostream>
using namespace std;
int main() {
//定义字符串
string str = "";
//确定字符串长度
str.length();
str.size();
//输入
getline(cin,str);//整行输入
cin>>str; //如果你的字符串中没有空格和字符串结束标志(\0)
//输出
cout<<str<<endl;
//1.赋值
//1.1初始化
string s1_1 = "hello";
cout<<s1_1<<endl;
//1.2采用函数赋值的方法;
s1_1.assign("world!");
cout<<s1_1<<endl;
//1.3截取字符串的方式
s1_1.assign(s1_1,1,3);
cout<<s1_1<<endl;
//1.4指定长度的重复字符
s1_1.assign(10,'A');
cout<<s1_1<<endl;
//2.字符串的拼接
//2.1 使用+
string s = "hell";
s = s + 'o';
cout<<s<<endl;
//2.2 使用函数push_back
//注意:传入的是一个字符而不是字符串,使用的是单引号
s.push_back(' ');
s.push_back('W');
cout<<s<<endl;
//2.3 拼接函数append();
s.append(" Xiaoming").append(" wwwww");
cout<<s<<endl;
//3.查找
//3.1使用find进行字符串的查找
string s3 = "hello world!w";
//当找到第一次出现的位置时,查找结束,返回字符起始位置。
int pos = s3.find("orl");
cout<<pos<<endl;
//3.2 从指定起始位置开始查找
int index = s3.find("w",6);
cout<<index<<endl;
//3.3 如果查找的字符不存在
//如果返回值为-1则表明查找不到
//string::npos 等价于 -1
int tmp = s3.find("lili");
cout<<tmp<<endl;
if(s3.find("lili") == string::npos) {
cout<<"no find"<<endl;
}
//3.4 反向查找(从后往前查找)
//rfind函数
string ss = "hello world wabc";
int t1 = ss.rfind("wa");//12
cout<<t1<<endl;
//3.5 查找的两种特殊用法
string ss1 = "abcdef12345abcd123456";
string ss2 = "123456789";
//在字符串ss1中查找字符串ss2的所有字符
//返回在字符串ss1中最起始的位置
int index1 = ss1.find_first_of(ss2);
cout<<index1<<endl;
//在字符串1中逆序查找(从后向前查找),查找不属于字符串2的字符
//返回第一个不属于字符串2的字符的位置
int index2 = ss1.find_last_not_of(ss2);
cout<<index2<<endl;
// 例子:寻找指定字符串中,最后一个字母的位置
string str1 = "abncjkadnkajbd123456akwdnka5466ajhdk789764";
string str2 = "0123456789";
int ans1 = str1.find_last_not_of(str2);
cout<<ans1<<endl;
return 0;
}