首頁  >  文章  >  後端開發  >  c++中strstr函數用法

c++中strstr函數用法

下次还敢
下次还敢原創
2024-05-09 03:51:21350瀏覽

C 中的 strstr() 函數在指定字串中搜尋子字串,傳回子字串中第一個字元的位置或 NULL。函數使用 KMP 演算法,先對子字串進行預處理,提高搜尋效率。

c++中strstr函數用法

C 中strstr() 函數用法

##定義與文法

strstr() 函數用於在一個字串中尋找另一個子字串的首次出現位置。其語法如下:

<code class="cpp">char *strstr(const char *str, const char *substr);</code>
其中:

  • str:要搜尋的字串。
  • substr:要尋找的子字串。

傳回值

如果找到子字串,strstr() 函數傳回包含子字串第一個字元的字串指針,否則傳回

NULL

用法說明

strstr() 函數使用 KMP 演算法(Knuth-Morris-Pratt 演算法)進行字串比對。它先對子字串進行預處理,然後掃描字串,從而提高了搜尋效率。

範例用法

以下程式碼範例示範如何使用strstr() 函數:

<code class="cpp">#include <iostream>
#include <cstring>

using namespace std;

int main() {
  char str[] = "Hello, world!";
  char substr[] = "world";

  char *result = strstr(str, substr);

  if (result) {
    cout << "Substring '" << substr << "' found at position " << (result - str) << endl;
  } else {
    cout << "Substring not found" << endl;
  }

  return 0;
}</code>
輸出:

<code>Substring 'world' found at position 7</code>

#注意事項

    strstr() 函數區分大小寫。
  • 如果子字串為空,strstr() 函數將傳回原始字串的指標。
  • 如果子字串比字串長,strstr() 函數會傳回
  • NULL

以上是c++中strstr函數用法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn