C 语言 strchr() 函数

2025年3月31日 | 阅读 4 分钟

本节将讨论 C 编程语言中字符串头文件中的 strchr() 函数。strchr() 函数用于查找原始字符串中指定字符的第一次出现。换句话说,strchr() 函数检查原始字符串是否包含已定义字符。如果在字符串中找到该字符,它将返回一个指针值;否则,它将返回一个空指针。在使用 C 编程语言中的 strchr() 函数时,我们需要在程序中导入 <string.h> 头文件。

strchr() function in C

语法

在上述语法中,strchr() 函数有两个参数:str 和 ch。

str: str 表示要搜索字符的原始字符串。

ch: ch 是一个字符类型变量,表示在字符串 str 中搜索的字符。

返回值: 它返回一个指针值,其中包含给定字符串中字符的第一次出现。

演示 strchr() 函数用法的程序

让我们考虑一个示例来检查给定字符串中字符的出现。

Program1.c

输出

Original string is: Use strchr() function in C.
 The first occurrence of the 's' in 'Use strchr() function in C.' string is: 'e strchr() function in C.'

在上述程序中,我们将 str 参数传递给 strchr() 函数以搜索字符 's',当找到字符时,它返回一个指针 ptr 值。ptr 变量包含从原始字符串的指定字符开始的值,直到 ch 变量在字符串中未获得空字符。

使用 strchr() 函数和 if-else 语句搜索字符的程序

让我们考虑一个示例,使用 strchr() 函数和 if-else 语句在 C 编程语言的给定字符串中获取第一个字符的出现。

Program1.c

输出

Original string: "javatpoint"
 Please enter a character you want to search in the string: p

 'p' is found in "javatpoint"

第二次执行

Original string: "javatpoint"
 Please enter a character you want to search in the string: b

 'b' is not found in "javatpoint"

在上述程序中,我们传递字符串“javatpoint”以搜索指定字符。这里我们从用户那里获取字符“p”作为输入并在字符串中搜索。之后,if 语句使用 strchr() 函数检查字符的出现,如果存在则打印指定字符。否则,它表示在字符串中未找到该字符。

获取给定字符串中每个字符出现的程序

让我们考虑一个示例,使用 C 编程语言的 strchr() 函数和 while 循环打印给定字符串中每个字符的出现。

Program3.c

输出

Given character 'e' found at position 3
 Occurrence of the character 'e' : 1
 The occurrence of the character 'e' in the string " Welcome to the JavaTpoint site" is "elcome to the JavaTpoint site"

 Given character 'e' found at position 8	
 Occurrence of the character 'e' : 2
 The occurrence of the character 'e' in the string " Welcome to the JavaTpoint site" is "e to the JavaTpoint site"

 Given character 'e' found at position 15
 Occurrence of the character 'e' : 3
 The occurrence of the character 'e' in the string " Welcome to the JavaTpoint site" is "e JavaTpoint site"

 Given character 'e' found at position 31
 Occurrence of the character 'e' : 4
 The occurrence of the character 'e' in the string " Welcome to the JavaTpoint site" is "e"

下一个主题C 程序结构