C 庫 - strstr() 函式



C 庫的 strstr() 函式返回指向另一個字串中指定子字串的第一個索引的指標。strstr() 的主要目標是在較大的字串中搜索子字串,它有助於找到指定子字串的第一次出現。

語法

以下是 C 庫 strstr() 函式的語法:

char *strstr (const char *str_1, const char *str_2);

引數

此函式接受兩個引數:

  • str_1 - 這是主字串。

  • str_2 - 要在主字串(即 str_1)中搜索的子字串。

返回值

該函式根據以下條件返回值:

  • 如果在 str_1 中找到 str_2,則該函式返回指向 str_1 中 str_2 的第一個字元的指標;如果在 str_1 中未找到 str_2,則返回空指標。

  • 如果 str_2 為空字串,則返回 str_1。

示例 1

以下是 C 庫程式,它使用 strstr() 函式演示了子字串在主字串中的存在。

#include <stdio.h>
#include <string.h>

int main () {
   const char str[20] = "TutorialsPoint";
   const char substr[10] = "Point";
   char *ret;
   
   // strstr(main_string, substring)
   ret = strstr(str, substr);
   
   // Display the output
   printf("The substring is: %s\n", ret);
   
   return(0);
}

輸出

執行程式碼後,我們得到以下結果:

The substring is: Point

示例 2

在這裡,我們演示瞭如何使用 strstr() 函式在主字串中搜索子字串。

#include <stdio.h>
#include <string.h>

int main() {
   char str_1[100] = "Welcome to Tutorialspoint";
   char *str_2;
   str_2 = strstr(str_1, "ials");
   printf("\nSubstring is: %s", str_2);
   return 0;
}

輸出

以上程式碼產生以下結果:

Substring is: ialspoint

這裡,前四個字元表示給定字串的子字串。

示例 3

在下面的示例中,設定 if-else 條件以檢查子字串是否存在於主字串中。

#include <stdio.h>
#include <string.h>

int main(){
   char str[] = "It is better to live one day as a King";
   char target[] = "live";
   char *p = strstr(str, target);

   if (p)
        printf("'%s' is present in the given string \"%s\" at position %ld", target, str, p-str);
   else
        printf("%s is not present \"%s\"", target, str);

    return 0;
}

輸出

執行程式碼後,我們得到以下結果:

'live' is present in the given string "It is better to live one day as a King" at position 16
廣告