ฟังก์ชัน strstr() เป็นฟังก์ชันที่กำหนดไว้ล่วงหน้าในไฟล์ส่วนหัว "string.h" ซึ่งใช้สำหรับดำเนินการจัดการสตริง ฟังก์ชันนี้ใช้เพื่อค้นหาการเกิดขึ้นครั้งแรกของสตริงย่อย สมมติว่า str2 ในสตริงหลัก สมมติว่า str1
ไวยากรณ์
ไวยากรณ์ของ strstr() มีดังนี้ −
char *strstr( char *str1, char *str2);
พารามิเตอร์ของ strstr() คือ
str2 เป็นสตริงย่อยที่เราต้องการค้นหาในสตริงหลัก str1
ค่าส่งคืนของ strstr() คือ
ฟังก์ชันนี้ส่งคืนตัวชี้ที่อยู่ของสตริงย่อยที่เกิดขึ้นครั้งแรกซึ่งเรากำลังค้นหาหากพบในสตริงหลัก มิฉะนั้นจะคืนค่า null เมื่อไม่มีสตริงย่อยในสตริงหลัก
หมายเหตุ − ขั้นตอนการจับคู่ไม่รวมอักขระ null ('\0') แต่ฟังก์ชันจะหยุดเมื่อพบอักขระ null
ตัวอย่าง
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;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
String is found The occurrence of string 'tor' in 'Tutorials' is 'torials
ตอนนี้ มาลองใช้โปรแกรมอื่นของ strstr()
นอกจากนี้เรายังสามารถใช้ฟังก์ชันนี้เพื่อแทนที่บางส่วนของสตริงได้ ตัวอย่างเช่น หากเราต้องการแทนที่สตริง str1 หลังจากพบสตริงย่อย str2 เกิดขึ้นเป็นครั้งแรก
ตัวอย่าง
Input: str1[] = {“Hello India”}
str2[] = {“India”}
str3[] = {“World”}
Output: Hello World คำอธิบาย − เมื่อใดก็ตามที่พบ 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;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
Tutorialspoint