C/C++ 中的 strstr() 函式
strstr() 函式是“string.h”標頭檔案中一個預定義的函式,用於執行字串處理。此函式用於查詢子字串(例如 str2)在主字串(例如 str1)中的第一次出現。
語法
strstr() 的語法如下:
char *strstr( char *str1, char *str2);
strstr() 的引數為
str2 是我們希望在主字串 str1 中搜索的子字串
strstr() 的返回值為
如果在主字串中找到我們正在搜尋的子字串,則此函式返回該子字串第一次出現的地址指標;否則,如果子字串不存在於主字串中,則返回空值。
注意 - 匹配過程不包括空字元('\0'),而是當函式遇到空字元時停止。
示例
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() 的另一個應用。
我們還可以使用此函式替換字串的某一部分,例如,如果我們想在找到其子字串 str2 的第一次出現後替換字串 str1。
示例
Input: str1[] = {“Hello India”}
str2[] = {“India”}
str3[] = {“World”}
Output: Hello World解釋 - 每當在 str1 中找到 str2 時,它將被替換為 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP