C++ 中的 strstr()
strstr() 函式是 string.h 中的預定義函式。它用於在字串中查詢子字串的出現。此匹配過程在“\0”處停止,不包括它。
strstr() 的語法如下 −
char *strstr( const char *str1, const char *str2)
在上面的語法中,strstr() 在字串 str1 中找到字串 str2 的首次出現。實現 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 分別定義為“蘋果是紅色的”和“是”。這在下面給出 −
char str1[] = "Apples are red"; char str2[] = "are"; char *ptr;
指標 ptr 指向“蘋果是紅色的”中的“是”的第一個出現。這是使用 strstr() 函式完成的。此程式碼片段如下所示 −
ptr = strstr(str1, str2);
如果指標 ptr 包含一個值,則顯示 str1 中 str2 的位置。否則,它會顯示 ptr1 中沒有 ptr2 的出現。這在下面顯示 −
if(ptr) cout<<"Occurance of \""<< str2 <<"\" in \""<< str1 <<"\" is at position "<<ptr - str1 + 1; else cout<<"There is no occurance of \""<< str2 <<"\" in "<<str1;
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP