标准模板库(STL)向程序员提供了一个用于字符串操作的容器类。string 类不仅能够根据应用程 序的需求动态调整大小,还提供了很有用的辅助函数(方法),可帮助操作字符串,这让程序员能够在 应用程序中使用标准的、经过测试的可移植功能,并将其主要精力放在开发应用程序的重要功能上。

在 C++中,字符串是一个字符数组。简单的字符数组可这样定义:
char staticName [20];

为了避开 上面所示 静态数组的长度 限制,C++支持动态分配内存,因此可以如下定义更 动态的字符数组:
char* dynamicName = new char [arrayLen];

这定义了一个动态分配的字符数组,其长度由变量 arrayLen 的值指定,而这种值是在运行阶段确 定的,因此该数组的长度是可变的。然而,如果要在运行阶段改变数组的长度,必须首先释放以前分配给它的内存,再重新分配内存来存储数据。 这样往往会带来很多复杂和麻烦,实例化并初始化 string 对象时,无需关心字符串长度和内存分配细节。STL string 类的构造 函数将自动完成这些工作

用法

  1. std::string str2 ("Hello String!");
  2. // 同样,可使用一个 string 对象来初始化另一个:
  3. std::string str2Copy (str2);
  4. // 可让 string 的构造函数只接受输入字符串的前 n 个字符
  5. std::string strPartialCopy (constCStyleString, 5);
  6. // 使其包含指定数量的特定字符来初始化
  7. std::string strRepeatChars (10, 'a');


  1. #include <string>
  2. #include <iostream>
  3. int main()
  4. {
  5. using namespace std;
  6. const char* constCStyleString = "Hello String!";
  7. cout << "Constant string is: " << constCStyleString << endl;
  8. std::string strFromConst (constCStyleString); // constructor
  9. cout << "strFromConst is: " << strFromConst << endl;
  10. std::string str2 ("Hello String!");
  11. std::string str2Copy (str2);
  12. cout << "str2Copy is: " << str2Copy << endl;
  13. // Initialize a string to the first 5 characters of another
  14. std::string strPartialCopy (constCStyleString, 5);
  15. cout << "strPartialCopy is: " << strPartialCopy << endl;
  16. // Initialize a string object to contain 10 'a's
  17. std::string strRepeatChars (10, 'a');
  18. cout << "strRepeatChars is: " << strRepeatChars << endl;
  19. return 0;
  20. }

Constant string is: Hello String!
strFromConst is: Hello String!
str2Copy is: Hello String!
strPartialCopy is: Hello
strRepeatChars is: aaaaaaaaa

访问 std::string 的字符内容

  1. #include <string>
  2. #include <iostream>
  3. int main ()
  4. {
  5. using namespace std;
  6. string stlString ("Hello String");
  7. // Access the contents of the string using array syntax
  8. cout << "Dispaly elements in string using array-syntax: " << endl;
  9. for (size_t charCounter = 0; charCounter < stlString.length(); ++ charCounter)
  10. {
  11. cout << "Character [" << charCounter << " ] is : ";
  12. cout << stlString [charCounter] << endl;
  13. }
  14. cout << endl;
  15. // Access the contents of a string using iterators
  16. cout << "Display elements in string using iterators: " << endl;
  17. int charOffset = 0;
  18. string::const_iterator charLocator;
  19. for (auto charLocator = stlString.cbegin(); charLocator != stlString.cend(); ++ charLocator)
  20. {
  21. cout << "Character [" << charOffset ++ << "] is : ";
  22. cout << *charLocator << endl;
  23. }
  24. cout << endl;
  25. // Access contents as a const char*
  26. cout << "The char* representation of the string is: ";
  27. cout << stlString.c_str () << endl;
  28. cout << endl;
  29. }

要访问 STL string 的字符内容,可使用迭代器,也可采用类似于数组的语法并使用下标运算符([]) 提供偏移量

拼接字符串

要拼接字符串,可使用运算符+=,也可使用成员函数 append():

  1. string sampleStr1 ("Hello");
  2. string sampleStr2 (" String! ");
  3. sampleStr1 += sampleStr2; // use std::string::operator+=
  4. // alternatively use std::string::append()
  5. sampleStr1.append (sampleStr2); // (overloaded for char* too)

使用加法赋值运算符(+=)或 append( )拼接字符串

  1. #include <string>
  2. #include <iostream>
  3. int main(){
  4. using namespace std;
  5. string sampleStr1 ("Hello");
  6. string sampleStr2 (" String!");
  7. // Concatenate
  8. sampleStr1 += sampleStr2;
  9. cout << sampleStr1 << endl << endl;
  10. string sampleStr3 (" Fun is not needing to use pointers!");
  11. sampleStr1.append (sampleStr3);
  12. cout << sampleStr1 << endl << endl;
  13. const char* constCStyleString = " You however still can!";
  14. sampleStr1.append (constCStyleString);
  15. cout << sampleStr1 << endl;
  16. return 0;
  17. }

Hello String!
Hello String! Fun is not needing to use pointers!
Hello String! Fun is not needing to use pointers! You however still can!

在 string 中查找字符或子字符串

STL string 类提供了成员函数 find(),该函数有多个重载版本,可在给定 string 对象中查找字符或 子字符串

  1. #include <string>
  2. #include <iostream>
  3. int main(){
  4. using namespace std;
  5. string sampleStr1 ("Hello");
  6. string sampleStr2 (" String!");
  7. // Concatenate
  8. sampleStr1 += sampleStr2;
  9. cout << sampleStr1 << endl << endl;
  10. string sampleStr3 (" Fun is not needing to use pointers!");
  11. sampleStr1.append (sampleStr3);
  12. cout << sampleStr1 << endl << endl;
  13. const char* constCStyleString = " You however still can! Fun Fun Fun";
  14. sampleStr1.append (constCStyleString);
  15. cout << sampleStr1 << endl << endl;
  16. size_t charPos = sampleStr1.find("Fun", 0); // 查找第一个出现 "day" 字符或者子字符串
  17. // size_t 类型名称非常直观,它的含义就是“size type”,大小的类型,也直接意味着它是sizeof运算符结果的类型
  18. if (charPos != string::npos) //npos是一个常数,表示size_t的最大值(Maximum value for size_t)
  19. {
  20. cout << "First instance of \"Fun\" was found at position " << charPos << endl << endl;
  21. }
  22. else
  23. {
  24. cout << "Substring not found." << endl << endl;
  25. }
  26. // 查找所有的 "Fun" 子串
  27. cout << "Locating all instances of substring \"Fun\" " << endl;
  28. size_t subStrPos = sampleStr1.find ("Fun", 0);
  29. while (subStrPos != string::npos)
  30. {
  31. cout << "\"Fun\" found at position " << subStrPos << endl;
  32. size_t searchOffset = subStrPos + 1;
  33. subStrPos = sampleStr1.find("Fun", searchOffset); // 通过 searchOffset查找
  34. }
  35. return 0;
  36. }

image.png

我们就通过指定偏移量,让 find()搜索下一个指定的子字符串

截短 STL string

STL string 类提供了 erase()函数,具有以下用途。
• 在给定偏移位置和字符数时删除指定数目的字符。

  1. string sampleStr ("Hello String! Wake up to a beautiful day!");
  2. sampleStr.erase (13, 28); // Hello String!

• 在给定指向字符的迭代器时删除该字符

  1. sampleStr.erase (iCharS); // iterator points to a specific character

字符串反转

假设要判断用户输入的字符串是否为回文,方法之一是将其反转, 再与原来的字符串进行比较。反转 STL string 很容易,只需使用泛型算法 std::reverse()
string sampleStr (“Hello String! We will reverse you!”);
reverse (sampleStr.begin (), sampleStr.end ());

  1. #include <string>
  2. #include <iostream>
  3. #include <algorithm>
  4. // reverse 是 <algorithm> 的实现
  5. int main()
  6. {
  7. using namespace std;
  8. string samplestr ("Hello String! we will reverse you!");
  9. cout << "the original sample string is: " << endl;
  10. cout << samplestr << endl << endl;
  11. reverse (samplestr.begin(), samplestr.end());
  12. cout << "After applying the std::reverse algorithm: " << endl;
  13. cout << samplestr << endl;
  14. return 0;
  15. }

the original sample string is:
Hello String! we will reverse you!

After applying the std::reverse algorithm:
!uoy esrever lliw ew !gnirtS olleH