Skip to content

Strings

std::string quản lý bộ nhớ tự động và dễ dùng hơn C string. Index bắt đầu từ 0. Nhiều hàm trả std::string::npos khi không tìm thấy.

std::string s = "hello";
std::size_t n = s.length();
MethodUse
length() / size()Độ dài
substr(pos, count)Cắt chuỗi
find(text)Tìm vị trí
erase(pos, count)Xóa đoạn
replace(pos, count, text)Thay đoạn
append(text) / +=Nối chuỗi
#include <iostream>
#include <string>
int main()
{
std::string s = "modern cpp";
auto pos = s.find("cpp");
if (pos != std::string::npos) {
s.replace(pos, 3, "C++");
}
std::cout << s.substr(0, 6) << ' ' << s << '\n';
}
  • Không kiểm tra npos trước khi dùng vị trí tìm được.
  • Nhầm length() là số byte với chuỗi Unicode.
  • Dùng operator[] ngoài biên, hành vi không xác định.

strings chuỗi std::string length substr find erase replace append npos