文章目录
字符串查找函数 strstr
实现查找一个子字符串在父字符串中的开始和结束位置的功能,可以通过使用标准库函数 strstr()
来完成。
strstr()
函数在父字符串中搜索第一次出现子字符串的位置,如果找到,它返回子字符串的第一个字符在父字符串中的指针;如果未找到,则返回 NULL
。
下面是一个 C 语言函数,它接收两个字符串作为参数,一个是要搜索的父字符串 a
,另一个是要找到的子字符串 sub
。这个函数将返回子字符串在父字符串中的开始和结束位置:
#include <stdio.h>
#include <string.h>
typedef struct {
int start_pos;
int end_pos;
} Position;
Position find_substring_positions(const char *a, const char *sub) {
Position pos = {-1, -1}; // 初始化为未找到的情形
const char *start = strstr(a, sub);
if (start != NULL) {
pos.start_pos = start - a; // 计算开始位置
pos.end_pos = pos.start_pos + strlen(sub) - 1; // 计算结束位置
}
return pos;
}
int main(void)
{
const char *a = "000001100110000011101110";
const char *sub = "01100110";
Position pos = find_substring_positions(a, sub);
if (pos.start_pos != -1 && pos.end_pos != -1) {
printf("Substring \"%s\" found in \"%s\" starting at position %d and ending at position %d.\n",
sub, a, pos.start_pos, pos.end_pos);
} else {
printf("Substring \"%s\" not found in \"%s\".\n", sub, a);
}
return 0;
}
在这个示例中,我们定义了一个 Position
结构来存储子字符串的开始和结束位置。函数 find_substring_positions
接受两个字符串参数,使用 strstr
函数查找子字符串在父字符串中的出现,并计算出它的开始和结束位置。
main
函数中,我们为父字符串 a
和子字符串 sub
声明了两个常量字符串,并调用了函数 find_substring_positions
来获取子字符串的位置。如果找到了子字符串,它将打印出子字符串的开始和结束位置;如果没有找到,则输出相应的消息。
当编译并运行这个程序,它会输出: Substring "01100110" found in "000001100110000011101110" starting at position 5 and ending at position 12.
这表示子字符串 "01100110"
在父字符串 "000001100110000011101110"
中从位置 5 开始,在位置 12 结束。位置索引是从 0 开始的。