所在头文件:<string>
实现:typedf basic_string<char> string
所在命名空间:std
功能:标准string提供字节标准容器的接口,同事增加对字符串中单独的字符的操作。由于标准string是basic_string<char>的一种特化,只能针对char型,如果字符编码方式是多字节或者可变字符序列(eg:UTF-8)那么它仍然按字节去解读,而不是按照传入内容的编码方式。
(1)成员函数number functions
| constructor(构造函数) | 创建string对象 (公有成员函数) | 
| destructor (析构函数) | 销毁string对象(公有成员函数) | 
| operator= (赋值运算符重载) | 将一个string对象赋给另一个string对象 (公有成员函数) | 
(2)Iterators
| begin | iterator begin(); const_iterator begin() const; | 返回一个迭代器指向string对象的第一个字符 | 
| end | iterator end() noexcept; const_iterator end() const noexcept; (noexcept是c11对异常的处理方式) | 返回一个迭代器指向string对象的结束字符的位置(‘\0’处),不可引用 如果是空串end=begin | 
| rbegin | reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; | 返回一个反向迭代器指向string对象的结束字符的位置 反向迭代器向后遍历-->向begin走 | 
| rend | reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; | 返回一个反向迭代器指向string对象的第一个字符的位置 | 
| cbegin | const_iterator cbegin() const noexcept; | 返回一个const迭代器指向string对象的第一个字符的位置 | 
| cend | const_iterator cend() const noexcept; | 返回一个const迭代器指向string对象的结束字符的位置 | 
| crbegin | const_reverse_iterator crbegin() const noexcept; | 返回一个const反向迭代器指向string对象的结束字符的位置 | 
| crend | const_reverse_iterator crend() const noexcept; | 返回一个const反向迭代器指向string对象的第一个字符的位置 | 
例子:
// string::begin/end
#include <iostream>
#include <string>
using namespace std:
void test1()
{
  string str ("Test string");
  for(string::iterator it=str.begin(); it!=str.end(); ++it)
  {
      cout << *it;
  }
  cout <<endl;
}
// string::rbegin/rend
void test2()
{
  string str ("now step live...");
  for(string::reverse_iterator rit=str.rbegin(); rit!=str.rend(); ++rit)
    cout << *rit;
}
// string::cbegin/cend
void test3()
{
  string str ("Lorem ipsum");
  for(autoit=str.cbegin(); it!=str.cend(); ++it)
    cout << *it;
  cout <<endl;
}
// string::crbegin/crend
void test4()
{
  string str ("lorem ipsum");
  for(auto rit=str.crbegin(); rit!=str.crend(); ++rit)
    cout << *rit;
   cout <<endl;
}
int main()
{
    test1();
    test2();
    test3();
    test4();
    return 0;
}(3)Capacity
| size | size_t size() const noexcept; | 返回string的字节个数(size_t类型) size!=capacity | 
| length | size_t length() const noexcept; | 返回string的字节个数(size_t类型) length!=capacity | 
| max_size | size_t max_size() const noexcept; | 返回string可以达到的最大长度 (极限范围,可能按max_size内存分配失败) max_size!=capacity | 
| resize | void resize (size_t n); void resize (size_t n, char c); | 重置string的长度,设置为n 重置string的长度,设置为n,内容用c填充 如果n<string的原length,超过n部分舍弃 如果n>string的原length,先拷贝原先的在加上 c的部分(没有c,就是空字符) | 
| capacity | size_t capacity() const noexcept; | 返回已分配给string的内存的字节个数 | 
| reverse | void reserve (size_t n = 0); | 改变string的capacity为n 不改变length和内容 | 
| clear | void clear() noexcept; | 清除string的内容,让string变成一个空串 length=0 | 
| empty | bool empty() const noexcept; | 返回string是否为空,为空返回true,非空返回 false | 
| shrink_to_fit | void shrink_to_fit(); | 减小string的capacity到size大小 | 
例子:
#include <iostream>
#include <string>
using namespace std;
// comparing size, length, capacity and max_size
void test1 ()
{
  string str ("Test string");
  cout <<"size: "<< str.size() <<endl;
  cout <<"length: "<< str.length() <<endl;
  cout <<"capacity: "<< str.capacity() <<endl;
  cout <<"max_size: "<< str.max_size() <<endl;
}
//string::shrink_to_fit
void test2()
{
  string str ("I like to code in C");
  cout << str <<endl;
  unsigned sz = str.size();
  str.resize (sz+2,‘+‘);
  cout << str <<endl;
  str.resize (14);
  cout << str <<endl;
}
// string::shrink_to_fit
void test3()
{
  string str (100,‘x‘);
  cout <<"1. capacity of str: "<< str.capacity() << endl;
  str.resize(10);
  cout <<"2. capacity of str: "<< str.capacity() <<endl;
  str.shrink_to_fit();
  cout <<"3. capacity of str: "<< str.capacity() <<endl;
}(4)Element access
| operator[] | char& operator[] (size_t pos); const char& operator[] (size_t pos) const; | 返回string[pos]的字符 | 
| at | char& at (size_t pos); const char& at (size_t pos) const; | 返回string[pop]的字符前会检查pos是不是字符范围内,超出范围会抛异常 | 
| back | char& back(); const char& back() const; | 返回最后一个字符的引用 | 
| front | char& front(); const char& front() const; | 返回第一个字符的引用 | 
例子:
#include <iostream>
#include <string>
using namespace std;
//string::operator[]
void test1()
{
    string str ("Test string");
    for(int i=0; i<str.length(); ++i)
    {
        cout << str[i];
    }
}
//string::at
void test2()
{
    string str("Test string");
    for(int i=0;i<str.size();i++)
    {
        cout<<str.at(i);
    }
}
//string::back
void test3()
{
    string str ("hello world.");
    str.back() =‘!‘;
    cout << str <<endl;
}
//string::front
void test4()
{
    string str ("test string");
    str.front() =‘T‘;
    cout << str <<endl;
}(5)Modifiers
| operator+= | string& operator+= (const string& str); string& operator+= (const char* s); string& operator+= (char n); string& operator+= (initializer_list<char> il); | 在现有的string后面添加字符串/字符 | 
| append | string& append (const string& str); string& append (const string& str, size_t subpos, size_t sublen); string& append (const char* s); string& append (const char* s, size_t n); string& append (size_t n, char c); template <class InputIterator> string& append (initializer_list<char> il); | 在现有的string后面添加字符串/字符 | 
| push_back | void push_back(char c); | 将字符c添加在string末尾,length++ | 
| assign | string& assign(const string& str); string& assign(const string& str, size_t subpos, size_t sublen); string& assign(const char * s); string& assign(const char *s,size_t n); string &assign(size_t n,char c); template<class InputIterator> string& assign(InputIterator first,InputIterator last); string& assign(initializer_list<char> il); | 将现有的字符串string替换成新的字符串 | 
| insert | string & insert (size_t pos,const string & str ); string & insert (size_t pos,const string & str,size_t subpos,size_t sublen); string & insert(size_t pos,const char *s); string & insert(size_t pos,const char *s,size_t n); string & insert(size_t pos,size_t n,char c); void insert (iterator p, size_t n, char c); iterator insert (iterator p, char c); template <class InputIterator> | 将现有字符串string的pos位置后面插入字符串或者字符 | 
| erase | string & erase(size_t pos=o,size_t len=pos); iterator erase(iterator p); iterator erase(iterator first,iterator last); | 将现有字符串删除一部分,length也有减少 | 
| replace | string & repalce(size_t pos,size_t len,const string& str); string & repalce(iterator i1,iterator i2,const string &str); string & repalce (size_t pos,size_t len,const string & str,size_t subpos,size_t sublen); string & replace(size_t pos,size_t len,const char *s); string & replace(iterator i1,iterator i2,const char *s); string & repalce(size_t pos,size_t len,const char*s,size_t n); string & repalce(iterator i1,iterator i2,const char*s,size_t n); string & raplace(size_t pos,size_t len,size_t n,char c); string & repalce(iterator i1,iterator i2,size_t n,chr c); template <class InputIterator> string & repalce(iterator i1, iterator i2,InputIterator first,InputIterator last); | 将现有字符串的一部分用新的字符串或者字符序列,字符去替换 | 
| swap | void swap(string & str); | 两个字符串的内容进行交换 | 
| pop_back | void pop_back(); | 将字符串末尾的字符删除 | 
例子:
#include <iostream>
#include <string>
using namespace std;
// string::operator+=
void test1()
{
  string name ("John");
  string family ("Smith");
  name +=" K. ";   // c-string
  name += family;  // string
  name +=‘\n‘;     // character
  cout << name;
}
//string::append
void test2()
{
  string str;
  string str2="Writing ";
  string str3="print 10 and then 5 more";
  //string& append(const string &str);
  str.append(str2);    //Writing
  //string& append(const string &str,size_t pos,size_t length);
  str.append(str3,6,3);//Writing 10 
  //string& append(const char* s,size_t n);
  str.append("dots are cool",5);//Writing 10 dots 
  //string& append(const char *s); 
  str.append("here: ");//Writing 10 dots here: 
  //string& append(size_t n,char c);
  str.append(10u,‘.‘);//Writing 10 dots here: ..........
  //strin& append(inputIterator first,inputIterator last);
  str.append(str3.begin()+8,str3.end());
  //Writing 10 dots here:......... and then 5 more
  //string& append(size_t n,)
  str.append<int>(5,0x2E);
  //Writing 10 dots here:......... and then 5 more.....
  cout << str <<endl;
}
//string::assign
void test3()
{
    string str;
    string str1 = “hello world”;
    
    str.assign(str1);
    cout << str << endl;
    str.assign(str1,7,5);
    cout << str << endl;
    str.assign("abcedf");
    cout << str << endl;
    str.assign("abcdrf",5);
    cout << str <<endl;
    str.assign(5u,‘.‘);
    cout <<str <<endl;
    cout << assign(str1.begin()+6,str1.end());
    cout << str << endl;
    str.assign<int>(10,0x2D);
    cout << str <<endl; 
    
}
//string::insert
void test4()
{
    string str="to be question";
    string str2="the ";
    string str3="or not to be";
    string::iterator it;// used in the same order as described above:
    str.insert(6,str2);// to be (the )question
    str.insert(6,str3,3,4);// to be (not )the question
    str.insert(10,"that is cool",8);// to be not (that is )the question
    str.insert(10,"to be ");// to be not (to be )that is the question
    str.insert(15,1,‘:‘);// to be not to be(:) that is the question
    it = str.insert(str.begin()+5,‘,‘);
    // to be(,) not to be: that is the question
    str.insert (str.end(),3,‘.‘);
    // to be, not to be: that is the question(...)
    str.insert (it+2,str3.begin(),str3.begin()+3);// (or )
    cout << str <<endl;
}
//string::erase
void test5()
{
    string str ("This is an example sentence.");
     cout << str <<endl;// "This is an example sentence."
     str.erase (10,8);
     cout << str <<endl;;// "This is an sentence."
     str.erase (str.begin()+9);       
     cout << str <<endl;;// "This is a sentence."
     str.erase (str.begin()+5, str.end()-9);
     std::cout << str <<endl;;// "This sentence."
}
//string::repalce
void test6()
{
  string base="this is a test string.";
  string str2="n example";
  string str3="sample phrase";
  string str4="useful.";
  // replace signatures used in the same order as described above:
  // Using positions:               
  string str=base;// "this is a test string."
  str.replace(9,5,str2);
  // "this is an example string." (1)
  str.replace(19,6,str3,7,6);
  // "this is an example phrase." (2)
  str.replace(8,10,"just a");
  // "this is just a phrase."     (3)
  str.replace(8,6,"a shorty",7);
  // "this is a short phrase."    (4)
  str.replace(22,1,3,‘!‘);
  // "this is a short phrase!!!"  (5)
  // Using iterators:                 
  str.replace(str.begin(),str.end()-3,str3);
  // "sample phrase!!!"      (1) 
   str.replace(str.begin(),str.begin()+6,"replace");
  // "replace phrase!!!"     (3)
  str.replace(str.begin()+8,str.begin()+14,"is coolness",7);
  // "replace is cool!!!"    (4)
  str.replace(str.begin()+12,str.end()-4,4,‘o‘);
  // "replace is cooool!!!"  (5)
  str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());
  // "replace is useful."    (6)
  std::cout << str <<endl;
}
//string::swap
void test7()
{
  string buyer ("money");
  string seller ("goods");
  cout <<"Before the swap, buyer has "<< buyer;
  cout <<" and seller has "<< seller <<endl;
  seller.swap (buyer);
  cout <<" After the swap, buyer has "<< buyer;
  cout <<" and seller has "<< seller <<endl;
}
//string::pop_back
void test8()
{
  string str ("hello world!");
  str.pop_back();
  cout << str <<endl;
}(6)String operations
| c_str | const char * c_str()const; | 返回一个const char *型的指针,内容是string的内容+‘\0’ | 
| data | const char * data()const; | 返回一个const char *型的指针,即得到string对象的c_string形式 | 
| get_allocator | allocator_type get_allocator()const; | 返回一个allocator——type型的string的拷贝 | 
| copy | size_t copy(char*s,size_t len,size_t pos=0)const; | 拷贝一个string中的子串到s所指的数组 (拷贝版不会自己添加‘\0‘) | 
| find | size_t find(cosnt string &str,size_t pos=0)const; size_t find(const char *s,size_t pos=0)const; size_t find(const char *s,size_t pos,size_t n)const; size_t find(char c,size_t pos=0)const; | 查找所找字符串序列第一次出现的位置 | 
| substr | string substr(size_t pos=0,size_t len=npos)const; | 返回子串 | 
| compare | int compare(const string& str)const; int compare(size_t pos,size_t len,const string &str)const; int compare(size_t pos,size_t len,const string &str,size_t subpos,size_t sublen)const; int compare(const char* s)const; int compare(size_t pos,size_t len,const char *s)const; int compare(size_t pos,size_tlen,const char *s,size_t n)const; | 比较两个字符串 | 
例子:
#include <iostream>
#include <string>
using namespace std;
//string::c_str()
void test1()
{
    string str ("Please split this sentence into tokens");
    char* cstr =newchar[str.length()+1];
    strcpy (cstr, str.c_str());
    // cstr now contains a c-string copy of str
    char* p = strtok (cstr," "); //线程不安全的字符串分割函数
    while(p!=0)
    {
      cout << p <<endl;      //依次输出Please split 直到NULL
      p = strtok(NULL," ");
    }
    delete[] cstr;
}
//string::data()
void test2()
{
    int length;
  string str ="Test string";
  char* cstr ="Test string";
  if( str.length() == std::strlen(cstr) )
  {
     cout <<"str and cstr have the same length."<<endl;
     if( memcmp (cstr, str.data(), str.length() ) == 0 )
      cout <<"str and cstr have the same content."<<endl;
  }
}
//string::copy
void test3 ()
{
  charbuffer[20];
  string str ("Test string...");
  size_t length = str.copy(buffer,6,5);
  buffer[length]=‘\0‘;
  cout <<"buffer contains: "<< buffer <<endl;
}
//string::compare
void test4()
{
  
  string str1 ("green apple");
  string str2 ("red apple");if(str1.compare(str2) != 0)
  cout << str1 <<" is not "<< str2 <<endl;
  if(str1.compare(6,5,"apple") == 0)
    cout <<"still, "<< str1 <<" is an apple"<<endl;
  if(str2.compare(str2.size()-5,5,"apple") == 0)
    cout <<"and "<< str2 <<" is also an apple"<<endl;
  if(str1.compare(6,5,str2,4,5) == 0)
    cout <<"therefore, both are apples"<<endl;
}(7)成员常量
| npos | size_t的最大范围 static const int npos=-1; (定义时就初始化) | 
(8)非成员函数的重载
| operator+ | 串联字符串 | 
| relational operator | 各种运算符的重载 | 
| swap | 交换两个字符串,std所属函数,非string所属 | 
| operator>> | 输入一个字符串 | 
| operator<< | 输出一个字符串 | 
| getline | 将输入的数据is传入到str字符串中,遇到定界符delim时停止 将输入的数据is传入到str字符串中,到文件结束 | 
本文出自 “momo就是辣么萌” 博客,请务必保留此出处http://momo462.blog.51cto.com/10138434/1761348
原文地址:http://momo462.blog.51cto.com/10138434/1761348