Bỏ qua để đến nội dung

Các phương thức của string

std::string cung cấp nhiều phương thức hữu ích để tìm kiếm, cắt, thay thế và biến đổi chuỗi.

#include <iostream>
#include <string>
int main() {
std::string s = "Hello, World!";
std::cout << s.find("World") << std::endl; // 7 (vị trí bắt đầu)
std::cout << s.find("xyz") << std::endl; // std::string::npos (không tìm thấy - số rất lớn)
if (s.find("World") != std::string::npos) {
std::cout << "Tim thay!" << std::endl;
}
return 0;
}
std::string s = "Hello, World!";
std::string sub = s.substr(7, 5); // Bắt đầu từ vị trí 7, lấy 5 ký tự
std::cout << sub << std::endl; // World
std::string rest = s.substr(7); // Từ vị trí 7 đến hết
std::cout << rest << std::endl; // World!

std::string không có sẵn phương thức chuyển hoa/thường - cần dùng <algorithm>:

#include <algorithm>
#include <string>
#include <iostream>
int main() {
std::string s = "Hello";
std::string upper = s;
std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
std::cout << upper << std::endl; // HELLO
std::string lower = s;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
std::cout << lower << std::endl; // hello
return 0;
}
std::string s = "Hello, World!";
s.replace(7, 5, "C++"); // Thay 5 ký tự từ vị trí 7 bằng "C++"
std::cout << s << std::endl; // Hello, C++!
s.insert(5, " there"); // Chèn " there" vào vị trí 5
std::cout << s << std::endl; // Hello there, C++!
s.erase(5, 6); // Xóa 6 ký tự từ vị trí 5
std::cout << s << std::endl; // Hello, C++!

Thư viện chuẩn không có sẵn phương thức tách chuỗi (split) - cách phổ biến là tự viết bằng std::stringstream kết hợp std::getline:

#include <sstream>
#include <vector>
#include <string>
#include <iostream>
std::vector<std::string> split(const std::string& s, char delimiter) {
std::vector<std::string> tokens;
std::stringstream ss(s);
std::string token;
while (std::getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::vector<std::string> words = split("apple,banana,orange", ',');
for (const std::string& w : words) {
std::cout << w << std::endl;
}
// apple
// banana
// orange
return 0;
}

Tương tự, không có sẵn hàm nối danh sách chuỗi thành một chuỗi - phải tự nối bằng vòng lặp hoặc std::ostringstream.

std::string s = "";
std::cout << s.empty() << std::endl; // 1 (true)
std::string a = "abc";
std::cout << (a == "abc") << std::endl; // 1 (true)
  • Các phương thức của std::string thao tác chủ yếu theo vị trí (index) trong chuỗi
  • Không có .split()/.join() sẵn - cần tự viết hoặc dùng std::stringstream
  • find() trả về std::string::npos (không phải -1) khi không tìm thấy