在C语言中字符串处理函数`strchr()`或`strstr()`用于在字符串中查找特定字符或子字符串的位置。
以下是这两个函数的基本用法:
1、strchr()
#include
char *strchr(const char *str, int c);
该函数在给定的字符串`str`中查找第一个出现的字符`c`,并返回其指针。如果未找到,则返回`NULL`。
例如:
#include
#include
int main() {
const char *str = "Hello, world!";
char *position = strchr(str, 'o');
if (position != NULL) {
printf("Found at position: %ld\n", position - str);
} else {
printf("Not found!\n");
}
return 0;
}
2、strstr()
#include
char *strstr(const char *haystack, const char *needle);
该函数在给定的字符串`haystack`中查找第一次出现的子字符串`needle`,并返回其指针。如果未找到,则返回`NULL`。
例如:
#include
#include
int main() {
const char *str = "Hello, world!";
char *position = strstr(str, "world");
if (position != NULL) {
printf("Found at position: %ld\n", position - str);
} else {
printf("Not found!\n");
}
return 0;
}
请注意,这些函数在找到匹配项时返回指向字符串中的位置的指针,并且返回的位置是相对于原始字符串起始位置的偏移量。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>