C语言寻找第2个子串位置
时间: 2024-02-06 16:26:55 浏览: 134
你可以使用C语言中的字符串函数来寻找第二个子串的位置。下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int find_second_substring(const char* str, const char* substr) {
int first_index = -1;
int second_index = -1;
// 寻找第一个子串的位置
char* first_occurrence = strstr(str, substr);
if (first_occurrence != NULL) {
first_index = first_occurrence - str;
}
// 在第一个子串之后寻找第二个子串的位置
if (first_index != -1) {
char* second_occurrence = strstr(str + first_index + 1, substr);
if (second_occurrence != NULL) {
second_index = second_occurrence - str;
}
}
return second_index;
}
int main() {
const char* str = "HelloHelloHello";
const char* substr = "Hello";
int second_index = find_second_substring(str, substr);
if (second_index != -1) {
printf("第二个子串的位置是:%d\n", second_index);
} else {
printf("找不到第二个子串\n");
}
return 0;
}
```
在上述示例中,函数`find_second_substring`会返回第二个子串在父串中的位置,如果找不到第二个子串,则返回-1。在`main`函数中,我们使用示例字符串"HelloHelloHello"和子串"Hello"来进行测试。输出结果将会是第二个子串的位置。
阅读全文
相关推荐

















