<string>

The essence of <string> is a dynamic array, essentially a std::vector<char>, that can conveniently operate text data.


#include <string>
#include <iostream>

int main() {
  std::string s1 = "Hello";
  std::string s2 = s2("World");
  std::string s3 = s1 + " " + s2;
  std::cout << s3 << std::endl;
}

Operations

  • 1.Assignment and append

std::string s = "abc";
s = "def";
s += "ghi";
s.append("jkl"); // Append

  • 2.Access

char c = s[0];
char c2 = s.at(0); // Will check the boundary, will trhow std::out_of_range error

  • 3.Length and Capacity

size_t len = s.size();
size_t cap = s.capacity();
bool empty = s.empty();
s.reserve(100); // Pre assign space
s.clear(); // Clear context

  • 4.Insert, Delete, Replace

s.insert(2, "AB");
s.erase(1, 3);
s.replace(0, 2, "XY");

  • 5.Find and Substr

size_t pos = s.find("XY"); // Will return the substring's position, and will throw std::string::npos error is not found
std::string sub = s.substr(1, 3);

  • 6.Compare

std::string a = "abc";
std::string b = "abd";

if (a == b) {
  // Logic...
}

if (a < b) {
  // Logic...
}

  • 7.C Style String

const char* cstr = s.c_str(); // To get the const char* pointer
char * data = s.data(); // To get the char* pointer (c++17)

  • 8.Foreach

std::string s = "hello";

for (size_t i = 0; i < s.size(); ++i) {
  std::cout << s[i];
}

for (char c : s) {
  std::cout << c;
}

for (auto it = s.begin; it != s.end(); ++it) {
  std::cout << *it;
}