gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
c语言查找字符串首次出现的函数
- User
c语言查找字符串首次出现的函数
- Assistant
在C语言中,可以使用
strchr()函数来查找字符串中首次出现某个字符的位置,它的原型如下:cchar *strchr(const char *str, int c);strchr()函数接受两个参数,第一个参数是要查找的字符串,第二个参数是要查找的字符。该函数返回一个指向被找到字符的指针,如果字符未找到,则返回NULL。示例代码如下:
c#include <stdio.h> #include <string.h> int main() { const char *str = "Hello, world!"; char c = 'o'; char *result = strchr(str, c); if (result != NULL) { printf("'%c' found at position %ld\n", c, result - str); } else { printf("'%c' not found\n", c); } return 0; }上述代码中,
strchr(str, c)会查找字符'o'在字符串"Hello, world!"中的首次出现位置,并且返回指向该位置的指针。如果找到了该字符,则计算出其相对于字符串起始位置的偏移,即(result - str),并输出结果。如果未找到该字符,则输出相应的提示信息。执行上述代码,输出结果为:
code'o' found at position 4