Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน strstr() ใน C++

strstr() หา Substring แรกที่พบใน String หลัก ประกาศใน <string.h>/<cstring> ส่งคืน Pointer ไปยังตำแหน่งที่เจอ หรือ NULL หากไม่เจอ

รูปแบบ

char* strstr(const char* haystack, const char* needle);

ตัวอย่างโค้ด

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

int main() {
    char str1[] = "Apples are red";
    char str2[] = "are";
    char* ptr = strstr(str1, str2);
    
    if (ptr)
        cout << "Found \"" << str2 << "\" in \"" << str1 
             << "\" at position " << (ptr - str1 + 1);
    else
        cout << "Not found";
    return 0;
}

ผลลัพธ์

Found "are" in "Apples are red" at position 8

การทำงาน

  • ptr - str1 = Offset (0-based) จากต้นสตริง
  • +1 แปลงเป็น 1-based Position
  • หยุดที่ \0 ไม่รวม Null Terminator

C++ String Version

#include <string>
#include <iostream>

int main() {
    std::string s1 = "Apples are red";
    std::string s2 = "are";
    size_t pos = s1.find(s2);
    if (pos != std::string::npos)
        std::cout << "Found at: " << pos + 1;
    else
        std::cout << "Not found";
}

ใช้ std::string::find() แทนใน C++ Modern Code