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

strstr() Function ใน C/C++


strstr() function เป็น predefined function ใน "string.h" header file ใช้ string handling ฟังก์ชันนี้หา first occurrence ของ substring (str2) ใน main string (str1)

Syntax

Syntax ของ strstr() −

char *strstr( char *str1, char *str2);

Parameters ของ strstr()

str2 คือ substring ที่ต้องการค้นหาใน main string str1

Return value ของ strstr()

คืนค่า address pointer ของ first occurrence ของ substring ที่หา ถ้าพบใน main string มิฉะนั้นคืนค่า null ถ้า substring ไม่อยู่ใน main string

Note − Matching process ไม่รวม null character('\0') หยุดเมื่อเจอ null character

ตัวอย่าง

Input: str1[] = {"Hello World"} str2[] = {"or"} Output: orld
Input: str1[] = {"tutorials point"} str2[] = {"ls"} Output: ls point

ตัวอย่าง

#include <string.h>
#include <stdio.h>
int main() {
    char str1[] = "Tutorials";
    char str2[] = "tor";
    char* ptr;
    // Will find first occurrence of str2 in str1
    ptr = strstr(str1, str2);
    if (ptr) {
        printf("String is found\n");
        printf("The occurrence of string '%s' in '%s' is '%s'", str2, str1, ptr);
    }
    else
        printf("String not found\n");
    return 0;
}

ผลลัพธ์

ถ้ารันโค้ดด้านบนจะได้ output −

String is found
The occurrence of string 'tor' in 'Tutorials' is 'torials

ตอนนี้ลอง application อื่นของ strstr()

เราสามารถใช้ฟังก์ชันนี้ substitute ส่วนหนึ่งของ string ได้ เช่น ถ้าต้องการ substitute str1 หลังจาก first occurrence ของ str2 ถูกพบ

ตัวอย่าง

Input: str1[] = {"Hello India"} str2[] = {"India"} str3[] = {"World"} Output: Hello World

Explanation − เมื่อเจอ str2 ใน str1 จะแทนที่ด้วย str3

ตัวอย่าง

#include <string.h>
#include <stdio.h>
int main() {
    // Take any two strings
    char str1[] = "Tutorialshub";
    char str2[] = "hub";
    char str3[] = "point";
    char* ptr;
    // Find first occurrence of st2 in str1
    ptr = strstr(str1, str2);
    // Prints the result
    if (ptr) {
        strcpy(ptr, str3);
        printf("%s\n", str1);
    }
    else
        printf("String not found\n");
    return 0;
}

ผลลัพธ์

ถ้ารันโค้ดด้านบนจะได้ output −

Tutorialspoint