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

Hàm strstr() trong C++

strstr() tìm lần xuất hiện đầu tiên của chuỗi con (substring) trong chuỗi. Header: <cstring> (C++) / <string.h> (C).

Cú pháp

const char* strstr(const char* haystack, const char* needle);
  • Trả về con trỏ đến vị trí tìm thấy
  • Trả về nullptr nếu không tìm thấy
  • Không bao gồm null terminator trong kết quả

Ví dụ cơ bản

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

int main() {
    const char* haystack = "Apples are red";
    const char* needle = "are";
    
    const char* pos = strstr(haystack, needle);
    
    if (pos) {
        size_t index = pos - haystack; // 0-based
        cout << "Tìm thấy '" << needle << "' tại vị trí " << index + 1 << " (1-based)\n";
        cout << "Phần còn lại: " << pos << '\n';
    } else {
        cout << "Không tìm thấy\n";
    }
    return 0;
}

Kết quả

Tìm thấy 'are' tại vị trí 8 (1-based)
Phần còn lại: are red

C++ Modern: std::string::find (Khuyến nghị)

#include <iostream>
#include <string>

int main() {
    std::string s = "Apples are red";
    std::string sub = "are";
    
    size_t pos = s.find(sub);
    if (pos != std::string::npos) {
        cout << "Vị trí (0-based): " << pos << '\n'; // 7
        cout << "Substring: " << s.substr(pos) << '\n'; // "are red"
    }
    
    // Tìm tất cả occurrences
    for (size_t p = s.find(sub); p != std::string::npos; p = s.find(sub, p + 1)) {
        cout << "Found at: " << p << '\n';
    }
    
    return 0;
}

C++23: std::string::contains (Chỉ check tồn tại)

if (s.contains("are")) { /* có */ } // C++23

So sánh strstr vs string::find

Ví dụ thực tế: Parse log line

#include <string>
#include <iostream>

void parseLog(const std::string& line) {
    // Tìm timestamp [HH:MM:SS]
    size_t bracket1 = line.find('[');
    size_t bracket2 = line.find(']');
    if (bracket1 != std::string::npos && bracket2 != std::string::npos) {
        std::string timestamp = line.substr(bracket1 + 1, bracket2 - bracket1 - 1);
        std::cout << "Timestamp: " << timestamp << '\n';
    }
    
    // Tìm level: ERROR, WARN, INFO
    const char* levels[] = {"ERROR", "WARN", "INFO"};
    for (const char* lvl : levels) {
        if (line.find(lvl) != std::string::npos) {
            std::cout << "Level: " << lvl << '\n';
            break;
        }
    }
}

Lưu ý

  • strstr phân biệt chữ hoa/thường (case-sensitive)
  • Case-insensitive: strcasestr (POSIX, không chuẩn) hoặc tự viết / dùng boost::algorithm::ifind_first
  • Performance: strstr dùng Two-Way algorithm (O(n+m)), khá nhanh
  • C++17: std::string_view cho zero-copy find
Đặc điểmstrstr (C)string::find (C++)
Inputconst char*std::string / string_view
Returnconst char*size_t (npos nếu không tìm thấy)
An toànCon trỏ thôType-safe, bounds checked
Null-terminatedBắt buộcKhông cần (string quản lý size)
UnicodeByte-level chỉByte-level (cần ICU cho grapheme)