输入两个字符串string1和string2,判断string2是否为string1的子串,如果是,返回string2在string1中第一次出现的位置的c语言程序
时间: 2024-03-24 11:14:45 浏览: 25
以下是针对你的问题的代码:
```c
#include <stdio.h>
#include <string.h>
int isSubstring(char* string1, char* string2) {
int len1 = strlen(string1);
int len2 = strlen(string2);
for(int i = 0; i <= len1-len2; i++) {
if(strncmp(&string1[i], string2, len2) == 0) {
return i;
}
}
return -1;
}
int main() {
char string1[100];
char string2[100];
int result;
printf("请输入两个字符串:\n");
scanf("%s%s", string1, string2);
result = isSubstring(string1, string2);
if(result == -1) {
printf("string2不是string1的子串\n");
} else {
printf("string2在string1中第一次出现的位置是:%d\n", result);
}
return 0;
}
```
该代码使用了一个isSubstring函数来判断string2是否为string1的子串,并返回string2在string1中第一次出现的位置。在主函数中,先输入两个字符串,然后调用isSubstring函数进行判断。最后根据返回值输出对应信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)