string是STL中的字符串,雖然有點慢,但很多時候都很有用…
一、string的構造函數
//生成空串
default (1) string();
//生成字符串爲str的複製品
copy (2) string (const string& str);
//將字符串str中從下標pos開始、長度爲len的部分作爲字符串初值
substring (3) string (const string& str, size_t pos, size_t len = npos);
//生成內容和C的char*類型一樣的字符串
from c-string (4) string (const char* s);
//以C的char*類型s的前char_len個字符串作爲字符串s的初值
from buffer (5) string (const char* s, size_t n);
//生成n個c字符的字符串
fill (6) string (size_t n, char c);
此外還有:
//生成一個相應位置的長度爲len的子串
string substr (size_t pos = 0, size_t len = npos) const;
二、string的大小和容量
size
length :Return length of string 返回string對象的長度(字符個數)
max_size:Return maximum size of string 返回string對象最大的字符容量
resize :Resize string 調整字符串的容量大小
capacity:Return size of allocated storage (public member function ) 返回已經分配的內存空間
clear :Clear string (public member function ) 清空字符串
empty :Test if string is empty (public member function ) 判斷字符串是否爲空
#include <iostream>
#include <string>
using namespace std;
int main() {
string s("123456789");
cout << "size = " << s.size() << endl;
cout << "length = " << s.length() << endl;
cout << "max_size = " << s.max_size() << endl;
cout << "capacity = " << s.capacity() << endl;
s.resize(14);
cout << "size = " << s.size() << endl;
cout << "length = " << s.length() << endl;
cout << "max_size = " << s.max_size() << endl;
cout << "capacity = " << s.capacity() << endl;
return 0;
}
三、string的字符串比較
用c的char*
時只能用strcmp,麻煩,而string支持>, >=, <, <=, ==, !=
的比較,甚至支持string和char*
的比較,這種比較是根據字典序的,從前往後。一般這樣比較就可以了。
四、string的字符訪問
operator[]
Get character of string (public member function )
at
Get character in string (public member function )
back
Access last character (public member function )
front
Access first character (public member function )
可以用下標和at,當然,最常用的還是下標。
void test6()
{
string s1("abcdef"); // 調用一次構造函數
// 方法一: 下標法
for( int i = 0; i < s1.size() ; i++ )
cout<<s1[i];
cout<<endl;
// 方法二:正向迭代器
string::iterator iter = s1.begin();
for( ; iter < s1.end() ; iter++)
cout<<*iter;
cout<<endl;
// 方法三:反向迭代器
string::reverse_iterator riter = s1.rbegin();
for( ; riter < s1.rend() ; riter++)
cout<<*riter;
cout<<endl;
}
五、string的修改
operator+=
Append to string (public member function ) 添加字符串
append
Append to string (public member function ) 添加字符串
push_back
Append character to string (public member function ) 添加字符到字符串尾部
pop_back
Delete last character (public member function ) 刪除尾部字符
最常用的還是+=,還有+,以及append。
六、string的刪除erase
1. iterator erase(iterator p); //刪除字符串中p所指的字符
//刪除字符串中迭代器區間[first,last)上所有字符
2. iterator erase(iterator first, iterator last);
//刪除字符串中從索引位置pos開始的len個字符
3. string& erase(size_t pos = 0, size_t len = npos);
七、string的查找:find
//在當前字符串的pos索引位置開始,查找子串s,返回找到的位置索引, -1表示查找不到子串
1. size_t find (constchar* s, size_t pos = 0) const;
2. npos
Maximum value for size_t 無法找到子串時返回的標誌