定义与初始化

string s1;
string s2{ "Hello" };
string s3(s2);
string s4(s2, 0, 2);   // 左闭右开

元素访问

  • at[]frontback
cout << s1.at(0) << endl;           // H,有边界检查
cout << s1[0] << endl;              // H,有边界检查
cout << s1.front() << endl;         // H
cout << s1.back() << endl;          // o
  • substr 切片
cout << s1.substr(0, 3) << endl;    // Hel,左闭右开
cout << s1.substr(0, 10) << endl;   // Hello,无边界检查

类型转换

C类型的char*, char[]

  • c_strdata
  • 直接赋值
string s{ "Hello" };
char arr[8];                        // C语言类型的字符数组
auto temp1 = s.c_str();             // 类型 const char*
strcpy_s(arr, temp1);               // 复制到独立内存
cout << sizeof(arr) << endl;        // sizeof = 8,内存大小
cout << sizeof(temp1) << endl;      // sizeof = 4,字符型指针 x86
cout << strlen(arr) << endl;        // strlen = 5,字符串长度,到'\0'截止
cout << strlen(temp1) << endl;      // strlen = 5,所指向的字符串长度,到'\0'截止

auto temp2 = s.data();				// 类型 const char*
strcpy_s(arr, temp2);               // 复制到独立内存
cout << sizeof(arr) << endl;        // sizeof = 8
cout << sizeof(temp2) << endl;      // sizeof = 4
cout << strlen(arr) << endl;        // strlen = 5
cout << strlen(temp2) << endl;      // strlen = 5
char arr[] = {"Hello"};
string ret = arr;

const char* p = "Hello";
string p_str = p;

数值转换

  • std::stoistolstoulstofstod
  • std::to_string
string str1 = "31337 with words";
auto ret1 = stoi(str1);             // int 31337
auto ret2 = stol(str1);             // long 31337

string str2 = "3.1415";
auto ret3 = stof(str2);             // float 3.1415
auto ret4 = stod(str2);             // double 3.1415

string str3 = "Pi is 3.1415";
//auto ret5 = stof(str4); // error
//auto ret6 = stod(str4); // error
float pi = 3.1415f;
auto str_pi = to_string(pi);        // string
printf(str_pi.c_str());             // 3.141500
printf(str_pi.data());              // 3.141500

成员函数

迭代器

  • beginend
  • rbeginrend
  • 迭代器即是指针变量
string s{"Example"};
auto s0 = s.begin();                // std::string::iterator
cout << *s0 << endl;                // E
cout << *--s.end() << endl;         // e
//cout << *s.end() << endl; // 报错

容量

  • empty 判断是否为空
  • sizelength 字符长度
  • max_size 所支持的最大字符长度
  • capacity 当前所分配的内存空间可容纳的最大字符长度
s = "Hi";
cout << s.empty() << endl;          // bool 0
cout << s.size() << endl;           // 2
cout << s.length() << endl;         // 2
cout << s.max_size() << endl;       // 2147483647
cout << s.capacity() << endl;       // 15

copy

  • copy(char* ptr, count, off=0)
string name = "Li Ming";
char A[10]{}, B[10]{};
name.copy(A, 2);
name.copy(B, 4, 3);
cout << A << endl;  // 遇到空字符'\0'截止 Li
cout << B << endl;  // 遇到空字符'\0'截止 Ming

注意:strlen不计算空字符

增删改查

  • append
  • operator+
  • push_back(ch) 单字符
  • insert(off, string)
  • insert(off, count, ch)
basic.append(5, '-');         // 追加n个相同字符
basic.append("append");       // 追加整个字符串
basic += "append";            // 追加整个字符串

basic = "xampl";
basic.insert(0, "E");       // 双引号,插入整个字符串
basic.insert(6, 1, 'e');    // 单引号,插入n个相同字符

  • pop_back 尾部单字符
  • clear 清空所有元素,不释放内存
  • erase(pos)
  • erase(pos, count)
s = "Exemple";
auto capacity = s.capacity();
s.clear();
assert(s.capacity() == capacity);
assert(s.empty());
assert(s.size() == 0);

s = "Exemple";
s.erase(0, s.size());
cout << s.empty() << endl;		 // 1
cout << s.capacity() << endl;    // 15 不释放内存

  • resize(newsize, ch='\0')
string long_string = "Where is the end?";
long_string.resize(8);             // 缩短
cout << long_string << endl;       // Where is

string short_string = "Ha";
short_string.resize(8);            // 延长,默认补全空字符'\0'
cout << short_string << endl;      // Ha

short_string = "Ha";
short_string.resize(8, 'a');       // 延长,补全字符'a'
cout << short_string << endl;      // Haaaaaaa

  • std::swap(left, right)
string a = "AAA";
string b = "BBBBBB";
swap(a, b);
cout << a << b << endl;     // BBBBBBAAA
a.swap(b);
cout << a << b << endl;     // AAABBBBBB

  • find(ch/char*)rfind
  • find(ch/char*, off)rfind
sentence = "The quick brown fox jumps over the lazy dog.";
cout << sentence.find("fox") << endl;                   // 16
cout << sentence.find("fox", 20) << endl;               // 4294967295 
cout << (signed int)sentence.find("fox", 20) << endl;   // -1

cout << sentence.find('o') << endl;                     // 12
cout << sentence.find('o', 20) << endl;                 // 26
  • replace 注意单字符与字符串的区别
string sentence{ "The quick brown fox jumps over the lazy dog." };
sentence.replace(10, 5, "red");
sentence.replace(sentence.begin(), sentence.begin() + 3, 1, 'A');
cout << sentence << endl;

比较

  • compare(string)
string c1{ "Batman" }, c2{ "Superman" };
auto result1 = c1.compare(c2);      // -1
auto result2 = c2.compare(c1);      // 1

cout << (c1 > c2) << endl;          // 0
cout << (c1 < c2) << endl;          // 1

应用

- 字母大小写转换

std::transform(str.begin(), str.end(), str.begin(), tolower);

附:ASCII 码