字符串使用方法整理 系列:
string 是 C++ STL 的一个字符串类型,原型是 vector<char>
并对字符串处理做了优化。
1. 声明
首先要包括库文件 #include <string>
,这个 <string>
不同于 <cstring>
,是 C++ 专有的库文件。
然后做出声明:
string str;
特殊的,可以赋予 string 初始值:
string a = "text";string b("text");string c = a; // 以 string 对 string 赋值也是可以的
2. 访问元素
2.1 直接访问
函数 .length() 可以得到该 string 的长度。
我们可以直接通过元素下标来访问某一个 string 中的字符,如 str[2]
访问第三个字符。
2.2 迭代器
我们也可以使用 vector<char>
相似的函数,如 .size() 是和 .length() 用途相同的函数。
我们也可以使用类似 vector<char>::iterator
的 string::iterator
迭代器来遍历字符串,如:
for (string::iterator i = str.begin(); i != str.end(); i++) { // do things here}
注意:同 vector 中的用法一样,通过迭代器遍历 string 时修改 string 的内容长度(如删除 string 中的字符)可能有意想不到的错误。
参考:C++ Reference 官网对 string 类中迭代器函数的定义如下:
begin: Return iterator to beginning (public member function )
end: Return iterator to end (public member function )
rbegin: Return reverse iterator to reverse beginning (public member function )
rend: Return reverse iterator to reverse end (public member function )
cbegin: Return const_iterator to beginning (public member function )
cend: Return const_iterator to end (public member function )
crbegin: Return const_reverse_iterator to reverse beginning (public member function )
crend: Return const_reverse_iterator to reverse end (public member function )
2.3 赋值函数
.assign(...) 赋值函数:
s.assign(str);s.assign(str, 1, 3); //如果str是"iamangel" 就是把"ama"赋给字符串s.assign(str, 2, string::npos); //把字符串str从索引值2开始到结尾赋给ss.assign("gaint");s.assign("nico", 5); //把’n’ ‘I’ ‘c’ ‘o’ ‘’赋给字符串s.assign(5, ’x’); //把五个x赋给字符串
3. 操作
3.1 清空 .clear()
用来清空 string。
3.2 判断空 .empty()
返回一个 boolean 值表示 string 是否为空。
3.3 取头部 .front()
返回首字符
3.4 取尾部 .back()
返回尾字符。
3.5 字符串相加
string 重载了 +
符号和 +=
符号,使用方法显而易见。+=
符号与 .append(...) 函数作用相同。如果注重函数式编程,推荐使用 .append(...) 函数。
3.6 插入 .insert(...)
.insert(...) 函数的作用是在字符串某处插入字符(串)。定义如下:
string (1)
string& insert (size_t pos, const string& str);substring (2)
string& insert (size_t pos, const string& str, size_t subpos, size_t sublen);c-string (3)
string& insert (size_t pos, const char* s);buffer (4)
string& insert (size_t pos, const char* s, size_t n);fill (5)
string& insert (size_t pos, size_t n, char c);void insert (iterator p, size_t n, char c);single character (6)
iterator insert (iterator p, char c);range (7)
templatevoid insert (iterator p, InputIterator first, InputIterator last);
C++ Reference 官网的例子:
// inserting into a string#include#include int main (){ std::string str="to be question"; std::string str2="the "; std::string str3="or not to be"; std::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 ) std::cout << str << '\n'; return 0;}
3.7 删除 .erase(...)
.erase(...) 函数可以删除指定位置的字符(串)。定义如下:
sequence (1)
string& erase (size_t pos = 0, size_t len = npos);
character (2)
iterator erase (iterator p);
range (3)
iterator erase (iterator first, iterator last);
举个例子(来自 C++ Reference):
// string::erase#include#include int main (){ std::string str ("This is an example sentence."); std::cout << str << '\n'; // "This is an example sentence." str.erase (10,8); // ^^^^^^^^ std::cout << str << '\n'; // "This is an sentence." str.erase (str.begin()+9); // ^ std::cout << str << '\n'; // "This is a sentence." str.erase (str.begin()+5, str.end()-9); // ^^^^^ std::cout << str << '\n'; // "This sentence." return 0;}
3.8 替换 .replace(...)
.replace(...) 函数定义:
string (1)
string& replace (size_t pos, size_t len, const string& str);string& replace (iterator i1, iterator i2, const string& str);substring (2)
string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);c-string (3)
string& replace (size_t pos, size_t len, const char* s);string& replace (iterator i1, iterator i2, const char* s);buffer (4)
string& replace (size_t pos, size_t len, const char* s, size_t n);string& replace (iterator i1, iterator i2, const char* s, size_t n);fill (5)
string& replace (size_t pos, size_t len, size_t n, char c);string& replace (iterator i1, iterator i2, size_t n, char c);range (6)
templatestring& replace (iterator i1, iterator i2, InputIterator first, InputIterator last);
举个例子(来自 C++ Reference):
// replacing in a string#include#include int main (){ std::string base="this is a test string."; std::string str2="n example"; std::string str3="sample phrase"; std::string str4="useful."; // replace signatures used in the same order as described above: // Using positions: 0123456789*123456789*12345 std::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: 0123456789*123456789* 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 << '\n'; return 0;}
4. 杂项
4.1 比较
通过 <, >, ==, <=, >=, != 六种比较符号,可以方便地在 string 之间、甚至是在 string 和 c-string 之间进行比较。
.compare(...) 支持多参数处理,支持用索引值和长度定位子串来进行比较。返回一个整数来表示比较结果,返回值意义如下:
0:相等
> 0:大于
< 0:小于
举例如下:
string s("abcd");s.compare("abcd"); //返回0s.compare("dcba"); //返回一个小于0的值s.compare("ab"); //返回大于0的值s.compare(s); //相等s.compare(0, 2, s, 2, 2); //用"ab"和"cd"进行比较 小于零s.compare(1, 2, "bcx", 2); //用"bc"和"bc"比较。
4.2 取子串 .substr(...)
取子串函数 .substr(...):
s.substr(); //返回s的全部内容s.substr(11); //从索引11往后的子串s.substr(5, 6); //从索引5开始6个字符
4.3 查找 .find(...)
.find(...) 函数的定义:
string (1)
size_t find (const string& str, size_t pos = 0) const;c-string (2)
size_t find (const char* s, size_t pos = 0) const;buffer (3)
size_t find (const char* s, size_t pos, size_t n) const;character (4)
size_t find (char c, size_t pos = 0) const;
返回值为字符串中第一个匹配的位置;如果没有找到则返回 string::npos
值。
样例(来自 C++ Reference):
// string::find#include// std::cout#include // std::stringint main (){ std::string str ("There are two needles in this haystack with needles."); std::string str2 ("needle"); // different member versions of find in the same order as above: std::size_t found = str.find(str2); if (found!=std::string::npos) std::cout << "first 'needle' found at: " << found << '\n'; found=str.find("needles are small",found+1,6); if (found!=std::string::npos) std::cout << "second 'needle' found at: " << found << '\n'; found=str.find("haystack"); if (found!=std::string::npos) std::cout << "'haystack' also found at: " << found << '\n'; found=str.find('.'); if (found!=std::string::npos) std::cout << "Period found at: " << found << '\n'; // let's replace the first needle: str.replace(str.find(str2),str2.length(),"preposition"); std::cout << str << '\n'; return 0;}
4.4 reserve 函数
参见:
Further reading:
- C++ Reference
- std::string