一、什麼是strstr函數
strstr函數是C語言標準庫中的一個字符串查找函數,用於在一個串中查找另一個串第一次出現的位置,返回第一次出現的位置指針。如果未找到,則返回NULL指針。
二、strstr函數的參數和返回值
strstr函數有兩個參數,第一個參數是被查找的字符串,第二個參數是要查找的字符串。函數返回值是一個指向被查找字符串中查找字符串首次出現位置的指針,如果查找不到則返回NULL。
const char *strstr(const char *str1, const char *str2);
三、如何使用strstr函數
使用strstr函數需要注意以下幾點:
1、首先需要引入庫。
2、函數參數順序是固定的,第一個參數是被查找的字符串,第二個參數是要查找的字符串。
3、函數返回的是指針,需要對返回值進行判斷,才能確定查找的字符串是否存在。
4、如果要查找的字符串為空,則返回被查找字符串的起始地址。
以下是一個示例代碼:
#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函數時,需要注意參數順序、對返回值進行判斷,以及針對不同的應用場景進行合適的組合使用。
原創文章,作者:WMRP,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/145981.html