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

Hàm strstr() trong C/C++


strstr() là hàm định sẵn trong "string.h" xử lý chuỗi. Tìm lần xuất hiện đầu tiên của chuỗi con (str2) trong chuỗi chính (str1).

Cú pháp

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

Tham số

str2 – chuỗi con cần tìm trong str1.

Giá trị trả về

Con trỏ đến lần xuất hiện đầu tiên của str2 trong str1 nếu tìm thấy, ngược lại trả về NULL.

Lưu ý – Quá trình khớp không bao gồm ký tự null ('\0'), hàm dừng khi gặp null.

Ví dụ

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

Ví dụ

#include 
#include 
int main() {
    char str1[] = "Tutorials";
    char str2[] = "tor";
    char* ptr;
    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;
}

Kết quả

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

Ứng dụng khác của strstr()

Thay thế phần chuỗi sau lần xuất hiện đầu tiên của str2 trong str1.

Ví dụ

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

Giải thích – Khi str2 tìm thấy trong str1, thay thế bằng str3.

Ví dụ

#include 
#include 
int main() {
    char str1[] = "Tutorialshub";
    char str2[] = "hub";
    char str3[] = "point";
    char* ptr;
    ptr = strstr(str1, str2);
    if (ptr) {
        strcpy(ptr, str3);
        printf("%s\n", str1);
    }
    else
        printf("String not found\n");
    return 0;
}

Kết quả

Tutorialspoint