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ề
nullptrnế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
| Đặc điểm | strstr (C) | string::find (C++) |
|---|---|---|
| Input | const char* | std::string / string_view |
| Return | const char* | size_t (npos nếu không tìm thấy) |
| An toàn | Con trỏ thô | Type-safe, bounds checked |
| Null-terminated | Bắt buộc | Không cần (string quản lý size) |
| Unicode | Byte-level chỉ | Byte-level (cần ICU cho grapheme) |