ฟังก์ชัน strstr() เป็นฟังก์ชันที่กำหนดไว้ล่วงหน้าใน string.h ใช้เพื่อค้นหาการเกิดขึ้นของสตริงย่อยในสตริง ขั้นตอนการจับคู่นี้จะหยุดที่ '\0' และไม่รวมอยู่ด้วย
ไวยากรณ์ของ strstr() มีดังนี้ −
char *strstr( const char *str1, const char *str2)
ในไวยากรณ์ข้างต้น strstr() จะค้นหาการเกิดขึ้นครั้งแรกของสตริง str2 ในสตริง str1 โปรแกรมที่ใช้ strstr() มีดังนี้ -
ตัวอย่าง
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char str1[] = "Apples are red";
char str2[] = "are";
char *ptr;
ptr = strstr(str1, str2);
if(ptr)
cout<<"Occurance of \""<< str2 <<"\" in \""<< str1 <<"\" is at position "<<ptr - str1 + 1;
else
cout<<"There is no occurance of \""<< str2 <<"\" in "<<str1;
return 0;
} ผลลัพธ์
ผลลัพธ์ของโปรแกรมข้างต้นเป็นดังนี้ −
Occurance of "are" in "Apples are red" is at position 8
ในโปรแกรมข้างต้น str1 และ str2 ถูกกำหนดด้วยค่า “Apples are red” และ “are” ตามลำดับ ด้านล่างนี้ −
char str1[] = "Apples are red"; char str2[] = "are"; char *ptr;
ตัวชี้ ptr ชี้ไปที่การเกิดขึ้นครั้งแรกของ "are" ใน "Apples are red" ทำได้โดยใช้ฟังก์ชัน strstr() ข้อมูลโค้ดสำหรับสิ่งนี้ได้รับด้านล่าง −
ptr = strstr(str1, str2);
หากตัวชี้ ptr มีค่า ตำแหน่งของ str2 ใน str1 จะปรากฏขึ้น มิฉะนั้น จะแสดงว่าไม่มี ptr2 เกิดขึ้นใน ptr1 ด้านล่างนี้ −
if(ptr) cout<<"Occurance of \""<< str2 <<"\" in \""<< str1 <<"\" is at position "<<ptr - str1 + 1; else cout<<"There is no occurance of \""<< str2 <<"\" in "<<str1;