Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Substring trong C++ (std::string::substr)

substr() trích xuất chuỗi con từ std::string. Cú pháp: str.substr(pos, len).

Cú pháp

std::string substr(size_t pos = 0, size_t len = npos) const;
  • pos: Vị trí bắt đầu (0-based). Nếu > size() → throw out_of_range
  • len: Số ký tự. Mặc định npos = đến hết chuỗi
  • Trả về string mới (copy)

Ví dụ cơ bản

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Apples are red";
    
    // Từ vị trí 11, lấy 3 ký tự
    string sub1 = str.substr(11, 3); // "red"
    
    // Từ đầu, lấy 6 ký tự
    string sub2 = str.substr(0, 6);  // "Apples"
    
    // Từ vị trí 7 đến hết
    string sub3 = str.substr(7);     // "are red"
    
    cout << "sub1: " << sub1 << '\n';
    cout << "sub2: " << sub2 << '\n';
    cout << "sub3: " << sub3 << '\n';
    
    return 0;
}

Kết quả

sub1: red
sub2: Apples
sub3: are red

Xử lý ngoại lệ

try {
    string s = "hi";
    string sub = s.substr(10, 5); // pos > size
} catch (const std::out_of_range& e) {
    cout << "Error: " << e.what() << '\n';
}

// An toàn hơn: check trước
if (pos <= s.size()) {
    auto sub = s.substr(pos, len);
}

C++17: std::string_view (Zero-copy substring)

#include <iostream>
#include <string>
#include <string_view>

int main() {
    std::string s = "Apples are red";
    
    // Không copy dữ liệu, chỉ view vào string gốc
    std::string_view sv1(s.data() + 11, 3); // "red"
    std::string_view sv2(s).substr(0, 6);   // "Apples" (C++17 string_view::substr)
    
    cout << "sv1: " << sv1 << '\n';
    cout << "sv2: " << sv2 << '\n';
    
    // Chuyển về string khi cần
    std::string owned = std::string(sv1);
    
    return 0;
}

So sánh string::substr vs string_view::substr

Các phương pháp khác lấy substring

Đặc điểmstd::string::substrstd::string_view::substr
Copy dữ liệuCó (allocation)Không (chỉ con trỏ + size)
Hiệu năngO(len)O(1)
LifetimeĐộc lậpPhụ thuộc string gốc
MutableCóKhông (read-only view)
C++ versionC++98C++17

Lưu ý Unicode

substr hoạt động trên code unit (byte cho UTF-8, char16_t cho UTF-16). Với UTF-8, có thể cắt giữa code point → invalid UTF-8. Cần ICU hoặc C++26 <text> cho grapheme cluster.

Phương phápCú phápGhi chú
substrs.substr(pos, len)Copy, standard
string_viewstd::string_view(s).substr(pos, len)Zero-copy, C++17
Iterator rangestring(s.begin()+pos, s.begin()+pos+len)Copy, flexible
C-stylestrncpy(dest, s.c_str()+pos, len)Không khuyến khích
Regexstd::regex_searchPattern-based, chậm