一、string类介绍
string类型是长度可变的字符串,C++标准库将负责管理与存储字符相关的内存,以及提供各种有用的操作 typedef basic_string<char> string; typedef basic_string<wchar_t> wstring; 要使用string类型对象,必须包含相关头文件 #include<string> usingstd::string;二、string对象的构造和初始化
string常用初始化例子:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a1("abcdefg");
cout<<a1<<endl;
basic_string<char> str;
string a2("abce",3);
cout<<a2<<endl;
string a3(a1,1,3);
cout<<a3<<endl;
//迭代器初始化
string::iterator first = a1.begin() + 1;
string::iterator last = a1.begin() + 5;
string a4(first, last);//[first, last)
cout<<a4<<endl;
return 0;
}
三、string常用的成员函数
常用的成员函数使用:
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
string s1("abcdefdg");
cout<<s1.size()<<endl;
cout<<s1.length()<<endl;
cout<<s1.empty()<<endl;
cout<<s1.substr(1,2)<<endl;
cout<<s1.substr(1)<<endl;
string::size_type pos = s1.find('d', 1);
if (pos == string::npos) cout<<"not found"<<endl;
else cout<<"pos="<<pos<<endl;
pos = s1.rfind('d');
if (pos == string::npos) cout<<"not found"<<endl;
else cout<<"pos="<<pos<<endl;
s1.replace(2, 2, "AAAAAA");
cout<<s1<<endl;
s1 = "abcdefg";
s1.replace(s1.begin()+1, s1.begin()+4, "AAAAAA");
cout<<s1<<endl;
string s2 = "xyzabc";
s2.insert(2,"MMMM");
cout<<s2<<endl;
s2.append("6666");
cout<<s2<<endl;
string s3="111";
s2.swap(s3);
cout<<s2<<endl;
cout<<s3<<endl;
//find_firset_of实现的是strinfo中第一个在strset中出现的位置
string strinfo=" //*---Hello World!......------";
string strset= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string::size_type first = strinfo.find_first_of(strset);
if(first == string::npos)
cout<<"not find any characters"<<endl;
string::size_type last = strinfo.find_last_of(strset);
if(last == string::npos)
cout<<"not find any characters"<<endl;
cout << strinfo.substr(first, last - first + 1)<<endl;
return 0;
}