一.strchr - 字符查找函数
1.函数原型
char *strchr(const char *str, int c);
2.核心功能
在字符串中查找特定字符的第一次出现位置
3.参数说明
参数 类型 说明
str const char* 要搜索的字符串
c int 要查找的字符(自动转换为char)
4.返回值
找到:返回指向该字符的指针
未找到:返回NULL
特殊:c = '\0' 时返回字符串结尾的空字符位置
5.用法示例
(1)基础查找
#include <stdio.h>
#include <string.h>
int main() {
const char *text = "Hello, World!";
char *ptr = strchr(text, 'W');
if(ptr) {
printf("找到 'W',位置: %ld\n", ptr - text); // 输出: 7
printf("后续内容: %s\n", ptr); // 输出: World!
} else {
printf("未找到字符\n");
}
return 0;
}
(2)查找文件扩展名
char filename[] = "document.pdf";
char *dot = strchr(filename, '.');
if(dot) {
printf("文件扩展名: %s\n", dot + 1); // 输出: pdf
} else {
printf("无扩展名\n");
}
(3)统计字符出现次数
int count_char(const char *str, char c) {
int count = 0;
const char *ptr = str;
while((ptr = strchr(ptr, c)) != NULL) {
count++;
ptr++; // 移动到下一个位置继续搜索
}
return count;
}
// 使用示例
char sentence[] = "She sells seashells by the seashore";
int s_count = count_char(sentence, 's');
printf("'s'出现次数: %d\n", s_count); // 输出: 7
二.strstr - 子串查找函数
1.函数原型
char *strstr(const char *haystack, const char *needle);
2.核心功能
在字符串中查找特定子串的第一次出现位置
3.参数说明
参数 类型 说明
haystack const char* 被搜索的主字符串
needle const char* 要查找的子字符串
4.返回值
找到:返回指向子串起始位置的指针
未找到:返回NULL
特殊:needle为空字符串时返回haystack
5.用法示例
(1)基础子串查找
#include <stdio.h>
#include <string.h>
int main() {
const char *text = "The quick brown fox jumps over the lazy dog";
char *found = strstr(text, "fox");
if(found) {
printf("找到子串,位置: %ld\n", found - text); // 输出: 16
printf("后续内容: %s\n", found); // 输出: fox jumps over...
} else {
printf("未找到子串\n");
}
return 0;
}
(2)检查文件类型
int is_image_file(const char *filename) {
const char *extensions[] = {".jpg", ".png", ".gif", ".bmp"};
for(int i = 0; i < 4; i++) {
if(strstr(filename, extensions[i]) != NULL) {
return 1; // 是图片文件
}
}
return 0; // 不是图片文件
}
// 使用示例
if(is_image_file("vacation.jpg")) {
printf("这是图片文件\n");
}
(3)提取HTML标签内容
void extract_html_content(const char *html) {
const char *start = strstr(html, "<title>");
if(!start) return;
start += 7; // 跳过"<title>"
const char *end = strstr(start, "</title>");
if(!end) return;
// 计算标题长度
size_t len = end - start;
char title[len + 1];
strncpy(title, start, len);
title[len] = '\0';
printf("页面标题: %s\n", title);
}
// 使用示例
extract_html_content("<html><title>Welcome Page</title></html>");
// 输出: 页面标题: Welcome Page
三.两函数对比分析
四.实际应用场景
1.命令行参数解析
int main(int argc, char *argv[]) {
int verbose = 0;
char *output_file = NULL;
for(int i = 1; i < argc; i++) {
if(strstr(argv[i], "--help")) {
print_help();
return 0;
}
else if(strstr(argv[i], "--verbose")) {
verbose = 1;
}
else if(strchr(argv[i], '=')) {
parse_key_value(argv[i]);
}
}
// ...
}
2.日志文件分析
void analyze_log(const char *logfile) {
FILE *file = fopen(logfile, "r");
if(!file) return;
char line[256];
int error_count = 0, warning_count = 0;
while(fgets(line, sizeof(line), file)) {
if(strstr(line, "[ERROR]")) error_count++;
else if(strstr(line, "[WARNING]")) warning_count++;
}
printf("错误数: %d\n警告数: %d\n", error_count, warning_count);
fclose(file);
}