一、什麼是strstr函數
strstr函數是C/C++中常用的一個函數,用於查找在一個字符串中是否存在另一個字符串(子串),如果存在,則返回子串在字符串中的起始地址,否則返回NULL。
函數的原型如下:
char *strstr(const char *str1, const char *str2);
其中,str1為被查找的字符串,str2為要查找的子串。
下面給出一個示例代碼:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[] = "Hello World!";
char substr[] = "Wo";
char *p = strstr(str, substr);
if (p != NULL) {
cout << "The substring is found at position: " << p - str << endl;
} else {
cout << "The substring is not found." << endl;
}
return 0;
}
上面的代碼中,首先定義了一個字符串str和一個子串substr,然後調用strstr函數查找子串在字符串中的位置,並輸出結果。運行結果為:
The substring is found at position: 6
二、strstr函數的實現原理
strstr函數的實現原理比較簡單,其基本思想是:
1、從起始地址開始逐個比較被查找字符串和查找字符串的字符;
2、如果被查找字符串中的一段子串和查找字符串相同,則返回子串在被查找字符串中的起始地址;
3、如果被查找字符串中不存在和查找字符串相同的子串,則返回NULL。
下面給出一個示例代碼,演示如何實現strstr函數:
#include <iostream>
#include <cstring>
using namespace std;
char *my_strstr(const char *str1, const char *str2)
{
while (*str1) {
const char *p1 = str1;
const char *p2 = str2;
while (*p1 && *p2 && (*p1 == *p2)) {
p1++;
p2++;
}
if (!*p2)
return (char *)str1;
str1++;
}
return NULL;
}
int main()
{
char str[] = "Hello World!";
char substr[] = "Wo";
char *p = my_strstr(str, substr);
if (p != NULL) {
cout << "The substring is found at position: " << p - str << endl;
} else {
cout << "The substring is not found." << endl;
}
return 0;
}
上面的代碼中,使用了兩個指針p1和p2,分別指向被查找字符串和查找字符串的字符,逐個比較它們的值。如果當前字符相同,則繼續比較下一個字符,直到被查找字符串中的一段子串和查找字符串相同,或者被查找字符串中的字符已經全部比較完畢為止。
三、注意事項
使用strstr函數查找子串時,需要注意以下幾點:
1、如果要在一個字符串中查找多個不同的子串,可以多次調用strstr函數,但需要注意每次查找的起始地址;
2、在比較字符串時,字符串中的字符需要逐個比較,不能使用字符串指針之間的比較,否則會出現錯誤;
3、當使用strstr函數查找子串時,需要保證被查找字符串和查找字符串都是合法的字符數組,否則會出現不可預料的錯誤。
四、總結
strstr函數是C/C++中常用的函數之一,它可以用於在一個字符串中查找另一個字符串(子串),並返回子串在字符串中的起始地址。在使用strstr函數時,需要注意比較字符串的方式以及被查找字符串和查找字符串的合法性,以免出現錯誤。
原創文章,作者:HUYS,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/149700.html
微信掃一掃
支付寶掃一掃