溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

解讀STL的string類中各方法的使用場景

發(fā)布時間:2020-07-22 21:10:59 來源:網(wǎng)絡 閱讀:2765 作者:momo462 欄目:移動開發(fā)

所在頭文件:<string>

實現(xiàn):typedf basic_string<char> string

所在命名空間:std

功能:標準string提供字節(jié)標準容器的接口,同事增加對字符串中單獨的字符的操作。由于標準string是basic_string<char>的一種特化,只能針對char型,如果字符編碼方式是多字節(jié)或者可變字符序列(eg:UTF-8)那么它仍然按字節(jié)去解讀,而不是按照傳入內(nèi)容的編碼方式。


(1)成員函數(shù)number functions

constructor(構(gòu)造函數(shù))創(chuàng)建string對象 (公有成員函數(shù))
destructor  (析構(gòu)函數(shù))銷毀string對象(公有成員函數(shù))
operator=  (賦值運算符重載)

將一個string對象賦給另一個string對象

(公有成員函數(shù))

(2)Iterators 

beginiterator begin();
const_iterator begin() const;
返回一個迭代器指向string對象的第一個字符
enditerator end() noexcept;

const_iterator end() const noexcept;

(noexcept是c11對異常的處理方式)

返回一個迭代器指向string對象的結(jié)束字符的位置(‘\0’處),不可引用

如果是空串end=begin

rbeginreverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;

返回一個反向迭代器指向string對象的結(jié)束字符的位置

反向迭代器向后遍歷-->向begin走

rendreverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;

返回一個反向迭代器指向string對象的第一個字符的位置

cbeginconst_iterator cbegin() const noexcept;
返回一個const迭代器指向string對象的第一個字符的位置
cendconst_iterator cend() const noexcept;
返回一個const迭代器指向string對象的結(jié)束字符的位置
crbeginconst_reverse_iterator crbegin() const noexcept;
返回一個const反向迭代器指向string對象的結(jié)束字符的位置
crendconst_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的字節(jié)個數(shù)(size_t類型)

size!=capacity

lengthsize_t length() const noexcept;

返回string的字節(jié)個數(shù)(size_t類型)

length!=capacity

max_sizesize_t max_size() const noexcept;

返回string可以達到的最大長度

(極限范圍,可能按max_size內(nèi)存分配失?。?/p>

max_size!=capacity

resize
void resize (size_t n);
void resize (size_t n, char c);

重置string的長度,設置為n

重置string的長度,設置為n,內(nèi)容用c填充

如果n<string的原length,超過n部分舍棄

如果n>string的原length,先拷貝原先的在加上

c的部分(沒有c,就是空字符)

capacity
size_t capacity() const noexcept;
返回已分配給string的內(nèi)存的字節(jié)個數(shù)
reversevoid reserve (size_t n = 0);

改變string的capacity為n

不改變length和內(nèi)容

clearvoid clear() noexcept;

清除string的內(nèi)容,讓string變成一個空串

length=0

emptybool empty() const noexcept;

返回string是否為空,為空返回true,非空返回

false

shrink_to_fitvoid 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是不是字符范圍內(nèi),超出范圍會拋異常
backchar& back();
const char& back() const;
返回最后一個字符的引用
frontchar& 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);

在現(xiàn)有的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 (InputIterator first, InputIterator last);

string& append (initializer_list<char> il);

在現(xiàn)有的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);

將現(xiàn)有的字符串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>
  void insert (iterator p, InputIterator first, InputIterator last);

將現(xiàn)有字符串string的pos位置后面插入字符串或者字符
erase

string & erase(size_t pos=o,size_t len=pos);

iterator erase(iterator p);

iterator erase(iterator first,iterator last);

將現(xiàn)有字符串刪除一部分,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); 


將現(xiàn)有字符串的一部分用新的字符串或者字符序列,字符去替換
swapvoid swap(string & str);
兩個字符串的內(nèi)容進行交換
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_strconst char * c_str()const;
返回一個const  char *型的指針,內(nèi)容是string的內(nèi)容+‘\0’
dataconst 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所指的數(shù)組

(拷貝版不會自己添加'\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;


查找所找字符串序列第一次出現(xiàn)的位置
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," "); //線程不安全的字符串分割函數(shù)
    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)非成員函數(shù)的重載

operator+串聯(lián)字符串
relational operator

各種運算符的重載

swap

交換兩個字符串,std所屬函數(shù),非string所屬

operator>>

輸入一個字符串

operator<<

輸出一個字符串

getline

將輸入的數(shù)據(jù)is傳入到str字符串中,遇到定界符delim時停止

將輸入的數(shù)據(jù)is傳入到str字符串中,到文件結(jié)束

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI