
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
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
廣告