Strings
Quick Notes
Section titled “Quick Notes”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.
Syntax
Section titled “Syntax”std::string s = "hello";std::size_t n = s.length();Common Methods
Section titled “Common Methods”| Method | Use |
|---|---|
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 |
Example
Section titled “Example”#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';}Common Mistakes
Section titled “Common Mistakes”- Không kiểm tra
npostrướ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.
Search Keywords
Section titled “Search Keywords”strings chuỗi std::string length substr find erase replace append npos