C语言增强版strstr函数实现:带可选段的模糊查询
C语言增强版strstr函数实现:带可选段的模糊查询
C语言有一个库函数:char *strstr(const char *haystack, const char *needle),该函数用于在字符串haystack中查找第一次出现字符串needle的位置,如果未找到则返回 null。本文将实现一个增强版的strstr函数,该函数支持带可选段的字符串模糊查询,并返回匹配子字符串在源字符串中的偏移量。
增强版strstr函数代码示例
#include <stdio.h>
#include <string.h>
int enhanced_strstr(const char *haystack, const char *needle, int start, int end) {
int haystack_len = strlen(haystack);
int needle_len = strlen(needle);
if (haystack_len < needle_len || start > haystack_len) {
return -1;
}
if (end == -1 || end > haystack_len) {
end = haystack_len;
}
for (int i = start; i <= end - needle_len; i++) {
int j;
for (j = 0; j < needle_len; j++) {
if (haystack[i + j] != needle[j]) {
break;
}
}
if (j == needle_len) {
return i - start;
}
}
return -1;
}
int main() {
char haystack[101];
char needle[101];
int start, end;
printf("Enter the haystack string: ");
fgets(haystack, sizeof(haystack), stdin);
haystack[strlen(haystack) - 1] = '\0';
printf("Enter the needle string: ");
fgets(needle, sizeof(needle), stdin);
needle[strlen(needle) - 1] = '\0';
printf("Enter the start index: ");
scanf("%d", &start);
printf("Enter the end index (-1 for end of string): ");
scanf("%d", &end);
int result = enhanced_strstr(haystack, needle, start, end);
if (result == -1) {
printf("Substring not found\n");
} else {
printf("Substring found at index %d\n", result);
}
return 0;
}
使用方法
使用该增强版的strstr函数,可以在指定的字符串中进行模糊查询。用户需要输入源字符串、要查找的子字符串、开始索引和结束索引(-1表示字符串的末尾)。程序会返回匹配子字符串相对于源字符串地址的偏移值。
代码说明
该函数的实现是基于C语言标准库中的strstr函数,并进行了相应的修改。主要修改如下:
- 添加了
start和end参数,用于指定模糊查询的范围。 - 函数返回值为匹配子字符串相对于源字符串地址的偏移值,而不是匹配子字符串的地址。
- 如果未找到匹配的子字符串,则返回-1。
总结
本文介绍了如何实现一个增强版的strstr函数,该函数支持带可选段的字符串模糊查询,并返回匹配子字符串在源字符串中的偏移量。代码示例展示了函数的具体实现以及使用方法。希望本文能够帮助大家更好地理解和使用strstr函数。
原文地址: https://www.cveoy.top/t/topic/cyil 著作权归作者所有。请勿转载和采集!