有两个字符串str1和str2,它们的长度都不超过100个字符。请编程实现在str1中查找str2的初始位置。
时间: 2023-06-06 20:06:25 浏览: 66
可以使用字符串匹配算法来实现查找,常见的有暴力匹配、KMP算法、BM算法等。这里给出一个简单的暴力匹配实现:
```python
def find_substring(s, sub):
for i in range(len(s) - len(sub) + 1):
j = 0
while j < len(sub) and s[i+j] == sub[j]:
j += 1
if j == len(sub):
return i
return -1 # 未找到子串
# 测试
s = 'hello, world'
sub = 'world'
pos = find_substring(s, sub)
print(pos) # 输出 7
```
上述代码中,循环遍历s中的每个字符,在每个位置i开始检查是否与sub匹配,若匹配成功,则返回匹配到的起始位置。如果遍历完成后仍未匹配到,则返回-1表示未找到。注意,如果str2中含有通配符或正则表达式等特殊字符,则需要使用更为复杂的匹配方式。
相关问题
有两个字符串str1和str2,它们的长度都不超过100个字符。请C语言编程实现在str1中查找str2的初始位置。
```
#include <stdio.h>
#include <string.h>
int main()
{
char str1[101], str2[101];
int len1, len2, i, j, flag;
printf("请输入字符串1:");
scanf("%s", str1);
printf("请输入字符串2:");
scanf("%s", str2);
len1 = strlen(str1);
len2 = strlen(str2);
for (i = 0; i <= len1 - len2; i++)
{
flag = 1;
for (j = 0; j < len2; j++)
{
if (str1[i + j] != str2[j])
{
flag = 0;
break;
}
}
if (flag)
{
printf("字符串2在字符串1中的初始位置为:%d\n", i);
return 0;
}
}
printf("字符串2不在字符串1中。\n");
return 0;
}
```
有两个字符串str1和str2,它们的长度都不超过100个字符。请使用C语言实现在str1中查找str2的初始位置。
可以使用strstr函数实现,在头文件string.h中已经定义。
具体代码如下:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[101], str2[101];
printf("请输入str1: ");
gets(str1);
printf("请输入str2: ");
gets(str2);
char *p = strstr(str1, str2);
if(p) {
printf("str2在str1中的初始位置为:%ld\n", p - str1);
} else {
printf("在str1中未找到str2\n");
}
return 0;
}
```
注意,gets函数已在C11标准中被弃用,建议使用fgets函数代替。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)