一、什么是strstr函数
strstr函数是C语言标准库中的一个字符串查找函数,用于在一个串中查找另一个串第一次出现的位置,返回第一次出现的位置指针。如果未找到,则返回NULL指针。
二、strstr函数的参数和返回值
strstr函数有两个参数,第一个参数是被查找的字符串,第二个参数是要查找的字符串。函数返回值是一个指向被查找字符串中查找字符串首次出现位置的指针,如果查找不到则返回NULL。
const char *strstr(const char *str1, const char *str2);
三、如何使用strstr函数
使用strstr函数需要注意以下几点:
- 首先需要引入
<string.h>
库。 - 函数参数顺序是固定的,第一个参数是被查找的字符串,第二个参数是要查找的字符串。
- 函数返回的是指针,需要对返回值进行判断,才能确定查找的字符串是否存在。
- 如果要查找的字符串为空,则返回被查找字符串的起始地址。 以下是一个示例代码:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "life is good";
char str2[10] = "is";
char *ret;
ret = strstr(str1, str2);
printf("The substring is: %s\n", ret);
return 0;
}
运行结果为:
The substring is: is good
四、strstr函数的一些应用场景
strstr函数可以用于字符串中子串的查找、替换以及判断字符串是否包含某个子串等场景。
五、应用示例1:截取字符串中的数字部分
假如我们有一个字符串,需要截取其中的数字部分,可以使用strstr函数以及其他字符串处理函数来实现:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char str[100] = "The price of the book is $12.99";
char *ptr = str;
int price;
// 查找数字部分的起始位置
while (!isdigit(*ptr))
ptr++;
// 用strstr函数查找数字部分字符串的末尾位置
char *end = strstr(ptr, ".");
if (end == NULL)
{
end = ptr + strlen(ptr);
}
// 截取数字部分字符串并转换为整型数
char temp[end - ptr + 1];
strncpy(temp, ptr, end - ptr);
temp[end - ptr] = '\0';
price = atoi(temp);
printf("The price is %d\n", price);
return 0;
}
运行结果为:
The price is 12
六、应用示例2:替换字符串中的指定子串
如果我们需要将一个字符串中的所有指定子串替换为新的字符串,也可以使用strstr函数的配合使用来实现:
#include <stdio.h>
#include <string.h>
void replace(char *str, const char *old_str, const char *new_str)
{
char *start = str;
char *end = NULL;
char buff[1024];
int len;
while ((end = strstr(start, old_str)) != NULL)
{
memset(buff, '\0', 1024);
strncpy(buff, start, end - start);
strcat(buff, new_str);
len = strlen(buff);
strcat(buff + len, end + strlen(old_str));
strcpy(str, buff);
start = str;
}
}
int main()
{
char str[1024] = "this is a good book. I like this book.";
printf("%s\n", str);
replace(str, "book", "movie");
printf("%s\n", str);
return 0;
}
运行结果为:
this is a good book. I like this book.
this is a good movie. I like this movie.
七、总结
strstr函数是一个常用的字符串查找函数,可以用于字符串中子串的查找、替换以及判断字符串是否包含某个子串等场景。在使用strstr函数时,需要注意参数顺序、对返回值进行判断,以及针对不同的应用场景进行合适的组合使用。