c语言中strchr()和strstr()函数怎么使用
在C语言中字符串处理函数`strchr()`或`strstr()`用于在字符串中查找特定字符或子字符串的位置。
以下是这两个函数的基本用法:
1、strchr()
#include char*strchr(constchar*str,intc);
该函数在给定的字符串`str`中查找第一个出现的字符`c`,并返回其指针。如果未找到,则返回`NULL`。
例如:
#include
#include
intmain(){
constchar*str="Hello,world!";
char*position=strchr(str,'o');
if(position!=NULL){
printf("Foundatposition:%ld\n",position-str);
}else{
printf("Notfound!\n");
}
return0;
}2、strstr()
#include char*strstr(constchar*haystack,constchar*needle);
该函数在给定的字符串`haystack`中查找第一次出现的子字符串`needle`,并返回其指针。如果未找到,则返回`NULL`。
例如:
#include
#include
intmain(){
constchar*str="Hello,world!";
char*position=strstr(str,"world");
if(position!=NULL){
printf("Foundatposition:%ld\n",position-str);
}else{
printf("Notfound!\n");
}
return0;
}请注意,这些函数在找到匹配项时返回指向字符串中的位置的指针,并且返回的位置是相对于原始字符串起始位置的偏移量。
版权声明
本文仅代表作者观点,不代表米安网络立场。
博豪信息



发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。