编写一个程序输入字符串判断字符串是否是子串C语言
时间: 2024-02-25 13:56:39 浏览: 40
下面是一个简单的程序,可以输入一个字符串和一个子串,判断子串是否在字符串中出现过:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100], substr[100];
printf("Enter a string: ");
scanf("%s", str);
printf("Enter a substring: ");
scanf("%s", substr);
if (strstr(str, substr) != NULL) {
printf("'%s' is a substring of '%s'\n", substr, str);
} else {
printf("'%s' is not a substring of '%s'\n", substr, str);
}
return 0;
}
```
该程序使用了 C 标准库中的 `strstr` 函数来查找子串是否在字符串中出现过。如果 `strstr` 函数返回值不为 `NULL`,则说明子串在字符串中出现过,否则说明子串不在字符串中出现过。
相关问题
用c语言编写一个程序判断一个字符串是否为另一个字符串的子串
好的,我可以帮你解答这个问题。
首先,我们需要明确子串的定义:一个字符串中的一段连续字符构成的字符串即为该字符串的子串。
那么,我们可以通过遍历原字符串的每个字符,判断是否与子串的第一个字符相等。如果相等,则继续比较后面的字符是否也相等,如果全部相等,则说明子串在原字符串中存在。
以下是一个用 C 语言实现的判断子串的函数:
```
int isSubstr(char *str, char *sub)
{
int i, j, flag;
for (i = 0; str[i] != '\0'; i++)
{
flag = 1;
for (j = 0; sub[j] != '\0'; j++)
{
if (str[i+j] != sub[j])
{
flag = 0;
break;
}
}
if (flag == 1)
{
return i;
}
}
return -1;
}
```
这个函数会返回子串在原字符串中的起始位置,如果没有找到则返回 -1。
调用这个函数的方法如下:
```
char str[] = "Hello, World!";
char sub[] = "World";
int pos = isSubstr(str, sub);
if (pos != -1)
{
printf("'%s' is a substring of '%s', starts at position %d\n", sub, str, pos);
}
else
{
printf("'%s' is not a substring of '%s'\n", sub, str);
}
```
这样就可以判断一个字符串是否为另一个字符串的子串了。
用c语言编写一个程序,输入两个字符串 s1 和 s2 ,判断 s2 是否是 s1 的子串,如果是,则输出 s2 在 s1 中的起始位置。否则输出 0
好的,以下是 C 语言代码实现:
```c
#include <stdio.h>
#include <string.h>
int find_substring(char *s1, char *s2) {
/*
判断字符串 s2 是否是 s1 的子串,如果是,则返回 s2 在 s1 中的起始位置,否则返回 0
*/
char *pos = strstr(s1, s2);
if (pos != NULL) {
return pos - s1 + 1;
} else {
return 0;
}
}
int main() {
char s1[100], s2[100];
printf("请输入字符串 s1:");
scanf("%s", s1);
printf("请输入字符串 s2:");
scanf("%s", s2);
int position = find_substring(s1, s2);
if (position != 0) {
printf("%s 是 %s 的子串,起始位置为 %d\n", s2, s1, position);
} else {
printf("%s 不是 %s 的子串\n", s2, s1);
}
return 0;
}
```
使用示例:
```
请输入字符串 s1:hello, world!
请输入字符串 s2:world
world 是 hello, world! 的子串,起始位置为 8
```
希望能够帮助到你!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)