一、什麼是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-tw/n/149700.html