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

ฟังก์ชัน strstr() ในภาษา C

ความหมาย

strstr() ใช้ค้นหาว่า substring (needle) ปรากฏใน string หลัก (haystack) หรือไม่ คืนค่า pointer ไปยังตำแหน่งแรกที่พบ หรือ NULL ถ้าไม่พบ

Prototype

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

พารามิเตอร์

  • haystack - string หลักที่ต้องการค้นหา
  • needle - substring ที่ต้องการค้นหา

คืนค่า

  • Pointer ไปยังตัวอักษรแรกของ substring ที่พบใน haystack
  • NULL ถ้าไม่พบ

ตัวอย่างโปรแกรมที่ 1: ค้นหา substring

#include <stdio.h>
#include <string.h>
int main() {
    char a[30], b[30];
    char *found;
    printf("ป้อน string หลัก: ");
    fgets(a, sizeof(a), stdin);
    a[strcspn(a, "\\n")] = '\\0'; // ลบ newline
    printf("ป้อน string ที่ต้องการค้นหา: ");
    fgets(b, sizeof(b), stdin);
    b[strcspn(b, "\\n")] = '\\0';
    found = strstr(a, b);
    if (found)
        printf("'%s' พบใน '%s' ที่ตำแหน่ง %ld\\n", b, a, found - a);
    else
        printf("ไม่พบ '%s' ใน '%s'\\n", b, a);
    return 0;
}

ผลลัพธ์ตัวอย่าง

ป้อน string หลัก: how are you
ป้อน string ที่ต้องการค้นหา: you
'you' พบใน 'how are you' ที่ตำแหน่ง 8

ตัวอย่างโปรแกรมที่ 2: ตรวจสอบว่ามี substring หรือไม่

#include <stdio.h>
#include <string.h>
int main() {
    char mainstring[50], substring[50];
    char *exists;
    printf("ป้อน string หลัก: ");
    fgets(mainstring, sizeof(mainstring), stdin);
    mainstring[strcspn(mainstring, "\\n")] = '\\0';
    printf("ป้อน substring ที่ต้องการตรวจสอบ: ");
    fgets(substring, sizeof(substring), stdin);
    substring[strcspn(substring, "\\n")] = '\\0';
    exists = strstr(mainstring, substring);
    if (exists)
        printf("'%s' มีอยู่ใน '%s'\\n", substring, mainstring);
    else
        printf("'%s' ไม่มีอยู่ใน '%s'\\n", substring, mainstring);
    return 0;
}

ผลลัพธ์ตัวอย่าง

ป้อน string หลัก: TutorialsPoint C Programming
ป้อน substring ที่ต้องการตรวจสอบ: Programming
'Programming' มีอยู่ใน 'TutorialsPoint C Programming'

หมายเหตุสำคัญ

  • ต้อง include <string.h>
  • การค้นหาเป็น case-sensitive (แยกตัวพิมพ์เล็ก-ใหญ่)
  • ไม่รวม null terminator ในการเปรียบเทียบ
  • คำนวณตำแหน่งได้จาก found - haystack (pointer arithmetic)
  • ไม่ควรใช้ gets() ใช้ fgets() แทน