使用c语言,设s、t 为两个字符串,两个字符串分为两行输出,判断t 是否为s 的子串。如果是,输出子串所在位置(第一个字符,字符串的起始位置从0开始),否则输出-1
时间: 2023-11-20 11:57:58 浏览: 84
可以使用C语言中的字符串函数strstr实现判断t是否为s的子串,如果是,返回子串在s中第一次出现的位置指针,否则返回NULL。
代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char s[100], t[100];
printf("请输入字符串s:");
scanf("%s", s);
printf("请输入字符串t:");
scanf("%s", t);
char *p = strstr(s, t);
if (p != NULL) {
int pos = p - s; // 计算子串在s中的位置
printf("%d\n", pos);
} else {
printf("-1\n");
}
return 0;
}
```
需要注意的是,如果使用gets函数输入字符串s和t,需要自己处理字符串末尾的换行符,否则会影响判断结果。可以使用fgets函数代替gets函数,fgets函数会读取输入的换行符。
相关问题
c语言设s、t为两个字符串,判断t是否为s的子串。如果是,输出子串所在位置(第一个字符),否则输出-1
你好!关于你的问题,我可以帮你解答。以下是 c 语言的代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char s[100], t[100];
int i, j, len_s, len_t;
printf("请输入字符串 s 和 t:\n");
scanf("%s%s", s, t);
len_s = strlen(s);
len_t = strlen(t);
for (i = 0; i <= len_s - len_t; i++) {
for (j = 0; j < len_t; j++) {
if (s[i+j] != t[j]) break;
}
if (j == len_t) {
printf("%d\n", i);
return 0;
}
}
printf("-1\n");
return 0;
}
```
这段代码可以接收两个字符串 s 和 t,并判断 t 是否为 s 的子串。如果是,输出子串在 s 中的位置,否则输出 -1。
希望我的回答能帮助到你!如果你有其他问题,欢迎提出。
用c语言写输入两个字符串s1s2判断s2是否为s1的子串
可以使用strstr函数来判断s2是否为s1的子串。该函数的原型为:
char *strstr(const char *s1, const char *s2);
其中s1是包含要查找的子串的字符串,s2是要查找的子串。如果s2是s1的子串,则该函数返回指向s1中第一个与s2匹配的位置的指针。如果s2不是s1的子串,则返回NULL指针。
下面是一个示例代码:
#include <stdio.h>
#include <string.h>
int main() {
char s1[100], s2[100];
printf("请输入字符串s1:");
scanf("%s", s1);
printf("请输入字符串s2:");
scanf("%s", s2);
if (strstr(s1, s2)) {
printf("s2是s1的子串。\n");
} else {
printf("s2不是s1的子串。\n");
}
return 0;
}
注意,该代码只能判断s2是否为s1的子串,而不能判断s2是不是s1的子序列(即不要求s2必须连续出现在s1中)。如果要判断s2是不是s1的子序列,可以使用更复杂的算法,比如动态规划。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)