Chapter 13.特殊容器string

string简介

string对象是一个特殊类型的容器,被设计用来操作字符串
与传统的c-string不同,传统的c-string是一个字符数组,而string对象属于一个类,类里面实现了大量的成员函数来更直观地操作字符串,同时很多有用的方法与C++容器都有相同的接口
string类是basic_string类模板的一个实例,在<string>中定义如下:
typedef basic_string<char> string;

构造函数
1.string ( );
2.string ( const string& str );
3.string ( const string& str, size_t pos, size_t n = npos );//第pos后的n个字符[pos从1开始到str.size()]
4.string ( const char * s, size_t n );
5.string ( const char * s );
6.string ( size_t n, char c );
7.template<class InputIterator> string (InputIterator begin, InputIterator end);

eg:
  string s0 ("Initial string");
  // constructors used in the same order as described above:
  string s1;
  string s2 (s0);
  string s3 (s0, 8, 3);
  string s4 ("A character sequence", 6);
  string s5 ("Another character sequence");
  string s6 (10, 'x');
  string s7a (10, 42);//*对应ascii的十进制值
  string s7b (s0.begin(), s0.begin()+7);
  cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
  cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6: " << s6;
  cout << "\ns7a: " << s7a << "\ns7b: " << s7b << endl;
Output:
s1: 
s2: iti
s3: str
s4: A char
s5: Another character sequence
s6: xxxxxxxxxx
s7a: **********
s7b: Initial
operator=
1.string& operator= ( const string& str );
2.string& operator= ( const char* s );
3.string& operator= ( char c );

Capacity:

emptyTest if string is empty
size/lengthReturn length of string
max_sizeReturn maximum size of string
resizeChange sizeResize string
capacityReturn size of allocated storage
reserveRequest a change in capacity
clearClear string

//resize
1.void resize ( size_t n, char c );
2.void resize ( size_t n );

eg:
  string str ("I like to code in C");
  cout << str << endl;
  size_t sz=str.size();
  str.resize (sz+2,'+');
  cout << str << endl;
Output:
I like to code in C
I like to code in C++

//reserve

  string str;
  size_t filesize;
  ifstream file ("test.txt",ios::in|ios::ate);
  filesize=file.tellg();
  str.reserve(filesize);
  file.seekg(0);
  while (!file.eof())
  {
    str += file.get();
  }
  cout << str;

Element access:

operator[]Get character in string
atGet character in string

Modifiers:

operator+=Append to string
appendAppend to string
push_backAppend character to string
assignAssign content to string
insertInsert into string
eraseErase characters from string
replaceReplace part of string
swap
Swap contents with another string

//+=
1.string& operator+= ( const string& str );//string
2.string& operator+= ( const char* s );//c-string
3.string& operator+= ( char c );//charactor

//append
1.string& append ( const string& str );
2.string& append ( const string& str, size_t pos, size_t n );
//str中的第一个元素pos为0,append范围为str [pos,n)
3.string& append ( const char* s, size_t n );
//复制s中的n个字符
4.string& append ( const char* s );
5.string& append ( size_t n, char c );
//n个character
6.template <class InputIterator>
string& append ( InputIterator first, InputIterator last );

eg:
	string app1("hello");
	string app2(" world");
2.
	app1.append(app2,0,app2.size());//复制[0,app.size())到app1
Output:
hello world
3.
	app1.append("C++",2);//复制两个字符,即C+
Output:
helloC+
5.
	app1.append(6,'h');//复制6个'h'到app1后
Output:
hellohhhhh
//push_back
void push_back ( char c );
eg:
  string str;
  ifstream file ("test.txt",ios::in);
  while (!file.eof())
  {
    str.push_back(file.get());
  }
  cout << str;
//assign
1.string& assign ( const string& str );
2.string& assign ( const string& str, size_t pos, size_t n );
//str中的第一个元素pos为0,assign范围为str [pos,n)
3.string& assign ( const char* s, size_t n );
4.string& assign ( const char* s );
5.string& assign ( size_t n, char c );
6.template <class InputIterator>
string& assign ( InputIterator first, InputIterator last );

eg:
2.
	string app1("hello");
	string app2(" world");
	app2.assign(app1,1,app1.size());//assign范围为[1,app1.size())
Output:
ello
//insert
1.string& insert ( size_t pos1, const string& str );
2.string& insert ( size_t pos1, const string& str, size_t pos2, size_t n );
3.string& insert ( size_t pos1, const char* s, size_t n);
4.string& insert ( size_t pos1, const char* s );
5.string& insert ( size_t pos1, size_t n, char c );
6.iterator insert ( iterator p, char c );
7.void insert ( iterator p, size_t n, char c );
8.template<class InputIterator>
void insert ( iterator p, InputIterator first, InputIterator last );

tips:
    pos1 & pos2都是从0开始
eg:
  string str="to be question";
              0123456789*123    //位置
  string str2="the ";
  string str3="or not to be";
               0123456789*123    //位置
  string::iterator it;

  // used in the same order as described above:1-8
  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 )    
1.在str的6位置处插入str2
2.在str的6位置处插入str3的3位置向后4位的字符
3.在str的10位置处插入that is cool的前8个字符,即 that空is空
4.在10位置处插入const char*
5.在15位置处插入一个:
6.在iterator处插入一个,
7.在str的iterator处插入3个.
8.iterator范围内的插入
//erase
1.string& erase ( size_t pos = 0, size_t n = npos );//erase掉pos后n个字符
2.iterator erase ( iterator position );
3.iterator erase ( iterator first, iterator last );

eg:
1.
  string str ("This is an example phrase.");
               0123456789*12345678
  string::iterator it;
  str.erase (10,8);
  cout << str << endl;        // "This is an phrase."
//replace
1.string& replace ( size_t pos1, size_t n1,   const string& str );
2.string& replace ( iterator i1, iterator i2, const string& str );
3.string& replace ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 );
4.string& replace ( size_t pos1, size_t n1,   const char* s, size_t n2 );
5.string& replace ( iterator i1, iterator i2, const char* s, size_t n2 );
6.string& replace ( size_t pos1, size_t n1,   const char* s );
7.string& replace ( iterator i1, iterator i2, const char* s );
8.string& replace ( size_t pos1, size_t n1,   size_t n2, char c );
9.string& replace ( iterator i1, iterator i2, size_t n2, char c );
10.template<class InputIterator>
string& replace ( iterator i1, iterator i2, InputIterator j1, InputIterator j2 );

eg:
  string base="this is a test string.";
  string str2="n example";
  string str3="sample phrase";
  string str4="useful.";
  // function versions used in the same order as described above:
  // Using positions:                 0123456789*123456789*12345
  string str=base;                // "this is a test string."
  str.replace(9,5,str2);          // "this is an example string."
  str.replace(19,6,str3,7,6);     // "this is an example phrase."
  str.replace(8,10,"just all",6); // "this is just a phrase."        复制6位
  str.replace(8,6,"a short");     // "this is a short phrase."       just a → a short
  str.replace(22,1,3,'!');        // "this is a short phrase!!!"


  // Using iterators:                      0123456789*123456789*
  string::iterator it = str.begin();   //  ^
  str.replace(it,str.end()-3,str3);    // "sample phrase!!!"
  str.replace(it,it+6,"replace it",7); // "replace phrase!!!"
  it+=8;                               //          ^
  str.replace(it,it+6,"is cool");      // "replace is cool!!!"
  str.replace(it+4,str.end()-4,4,'o'); // "replace is cooool!!!"
  it+=3;                               //             ^
  str.replace(it,str.end(),str4.begin(),str4.end());
                                       // "replace is useful."

String operations:

c_strGet C string equivalent
dataGet string data
get_allocatorGet allocator
copyCopy sequence of characters from string
findFind content in string
rfindFind last occurrence of content in string
find_first_ofFind character in string
find_last_ofFind character in string from the end
find_first_not_ofFind absence of character in string
find_last_not_ofFind absence of character in string from the end
substrGenerate substring
compareCompare strings

string::npos等于str.max_size()+1,即string最大的长度4294967294+1

//find    正向查找
//查找成功时返回所在位置,失败返回string::npos的值
1.size_t find ( const string& str, size_t pos = 0 ) const;    以另一个str来作find
2.size_t find ( const char* s, size_t pos, size_t n ) const;  以一个const char*的pos位置开始的n个字符串来find pos从0开始到str.size()-1
3.size_t find ( const char* s, size_t pos = 0 ) const;        以一个const char*的pos位置开始来作find
4.size_t find ( char c, size_t pos = 0 ) const;               以一个char的pos位置开始来作find

//rfind  反向查找
1.size_t rfind ( const string& str, size_t pos = npos ) const;
2.size_t rfind ( const char* s, size_t pos, size_t n ) const;
3.size_t rfind ( const char* s, size_t pos = npos ) const;
4.size_t rfind ( char c, size_t pos = npos ) const;

//find_first_of    正向查找
查找在string中出现的任何字符,返回第一次出现的位置
1.size_t find_first_of ( const string& str, size_t pos = 0 ) const;
2.size_t find_first_of ( const char* s, size_t pos, size_t n ) const;//从pos开始查找当前串中第一个在s的前n个字符组成的数组里的字符的位置。查找失败返回string::npos
3.size_t find_first_of ( const char* s, size_t pos = 0 ) const;
4.size_t find_first_of ( char c, size_t pos = 0 ) const;

//find_first_not_of
//从当前串中查找第一个不在串s中的字符出现的位置,失败返回string::npos
1.size_t find_first_not_of ( const string& str, size_t pos = 0 ) const;
2.size_t find_first_not_of ( const char* s, size_t pos, size_t n ) const;
3.size_t find_first_not_of ( const char* s, size_t pos = 0 ) const;
4.size_t find_first_not_of ( char c, size_t pos = 0 ) const;

//find_last_of    反向查找
1.size_t find_last_of ( const string& str, size_t pos = npos ) const;
2.size_t find_last_of ( const char* s, size_t pos, size_t n ) const;
3.size_t find_last_of ( const char* s, size_t pos = npos ) const;
4.size_t find_last_of ( char c, size_t pos = npos ) const;

//find_last_not_of
1.size_t find_last_not_of ( const string& str, size_t pos = npos ) const;
2.size_t find_last_not_of ( const char* s, size_t pos, size_t n ) const;
3.size_t find_last_not_of ( const char* s, size_t pos = npos ) const;
4.size_t find_last_not_of ( char c, size_t pos = npos ) const;

//c_str()返回一个字符数组+'\0'
//data()返回一个字符数组

//copy()
size_t copy ( char* s, size_t n, size_t pos = 0) const;
eg:
  char buffer[20];
  string str ("Test string...");
               0123456789*123  
  size_t length=str.copy(buffer,6,5);//从5位置处copy6个字符到buffer中
  buffer[length]='\0';
  cout << buffer << endl;
Output:
string
//substr()
string substr ( size_t pos = 0, size_t n = npos ) const;
eg:
	string str("hello C++");
	OutputDebugString(str.substr(6,3).c_str());
//compare
1.int compare ( const string& str ) const;
2.int compare ( const char* s ) const;
3.int compare ( size_t pos1, size_t n1, const string& str ) const;
4.int compare ( size_t pos1, size_t n1, const char* s) const;
5.int compare ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 ) const;
6.int compare ( size_t pos1, size_t n1, const char* s, size_t n2) const;

eg:
  string str1 ("green apple");
  string str2 ("red apple");
  if (str1.compare(str2) != 0)
    cout << str1 << " is not " << str2 << "\n";
  if (str1.compare(6,5,"apple") == 0)
    cout << "still, " << str1 << " is an apple\n";
  if (str2.compare(str2.size()-5,5,"apple") == 0)
    cout << "and " << str2 << " is also an apple\n";
  if (str1.compare(6,5,str2,4,5) == 0)
    cout << "therefore, both are apples\n";
Output:
green apple is not red apple
still, green apple is an apple
and red apple is also an apple
therefore, both are apples

getline
1.istream& getline ( istream& is, string& str, char delim );//遇到字符delim结束,并丢弃delim 
2.istream& getline ( istream& is, string& str );//遇到字符'\n'结束,并丢弃'\n' 

string str;
getline(cin,str,'a');//遇到字符'a'结束,并丢弃'a'
cout << str << endl;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值