C 庫 - strchr() 函式



C 庫的 strchr() 函式用於查詢給定字串中某個字元的首次出現位置。此函式可以處理空字元(\0)或以 null 結尾的字串。此函式在各種文字處理任務中很有用,使用者需要在其中找到特定的字元。

語法

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

char *strchr(const char *str, int search_str)

引數

此函式接受以下引數:

  • str - 此引數表示給定的字串。

  • search_str - 此引數指的是要在給定字串中搜索的特定字元。

返回值

此函式返回指向字串 (str) 中字元 “search_str” 首次出現位置的指標,如果未找到該字元,則返回 NULL。

示例 1

以下是一個基本的 C 庫程式,它演示瞭如何使用 strchr() 函式在給定字串中搜索字元。

#include <stdio.h>
#include <string.h>
int main () 
{
   const char str[] = "Tutorialspoint";
   // "ch" is search string
   const char ch = '.';
   char *ret;
   ret = strchr(str, ch);
   printf("String after |%c| is - |%s|\n", ch, ret);
   return(0);
}

輸出

執行上述程式碼後,我們得到的結果值為 null,因為在字串中沒有找到字元“.”。

String after |.| is - |(null)|

示例 2

在這裡,我們有一個特定的字元來確定從給定字串中提取子字串。

#include <stdio.h>
#include <string.h>
int main() 
{
   const char *str = "Welcome to Tutorialspoint";
   char ch = 'u';
   // Find the first occurrence of 'u' in the string
   char *p = strchr(str, ch);

   if (p != NULL) 
   {
       printf("String starting from '%c' is: %s\n", ch, p);
   } 
   else 
   {
       printf("Character '%c' not found in the string.\n", ch);
   }
   return 0;
}

輸出

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

String starting from 'u' is: utorialspoint

示例 3

在本例中,我們將找到給定字串中字元的位置。

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

int main() 
{
   char str[] = "This is simple string";
   char* sh;

   printf("Searching for the character in 's' in the given string i.e. \"%s\"\n", str);
   sh = strchr(str, 's');

   while (sh != NULL) 
   {
       printf("Found at position- %d\n", sh - str + 1);
       sh = strchr(sh + 1, 's');
   }
   return 0;
}

輸出

執行上述程式碼後,我們觀察到字元“S”在給定字串的不同位置出現了 4 次。

Searching for the character in 's' in the given string i.e. "This is simple string"
Found at position- 4
Found at position- 7
Found at position- 9
Found at position- 16
廣告