若str2是str1的子串,则返回str2在str1的首次出现的地址;如果str2不是str1的子串,则返回NULL。
时间: 2024-05-06 17:21:54 浏览: 18
C语言中可以使用库函数strstr()实现该功能。
函数原型为:
```c
char *strstr(const char *str1, const char *str2);
```
其中,str1是要查找的字符串,str2是要查找的子串。
函数返回值为指向str2在str1中首次出现的地址的指针,如果str2不是str1的子串,则返回NULL。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "hello world";
char str2[10] = "world";
char *p;
p = strstr(str1, str2);
if (p != NULL) {
printf("str2 is a substring of str1, position: %d\n", p - str1);
} else {
printf("str2 is not a substring of str1\n");
}
return 0;
}
```
输出结果为:
```
str2 is a substring of str1, position: 6
```
相关问题
它的作用是:若str2是str1的子串,则返回str2在str1的首次出现的地址;如果str2不是str1的子串,则返回NULL。 下面,请你设计算法简单实现函数strstr(),若存在返回子串首次出现的下标(从0开始),若不存在返回-1。
好的,我能够帮你设计算法简单实现函数strstr()。以下是我的实现:
```C++
int strstr(const char* str1, const char* str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);
if (len2 == 0) {
return 0;
}
for (int i = 0; i < len1; i++) {
if (str1[i] == str2[0]) {
int j;
for (j = 0; j < len2 && i + j < len1; j++) {
if (str1[i + j] != str2[j]) {
break;
}
}
if (j == len2) {
return i;
}
}
}
return -1;
}
```
这里我使用了双重循环,首先第一个循环遍历整个字符串 str1,第二个循环则对于每个位置 i,在 str1 中检查是否存在 str2 作为子串。如果在 str1 中找到了 str2,就返回 str2 在 str1 中第一次出现的下标。如果 str2 不是 str1 的子串,则返回 -1。
希望我的答案对你有所帮助。如果你还有其他问题,欢迎继续问我。
用C语言写一段代码,判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。
以下是一个简单的实现:
```c
#include <stdio.h>
#include <string.h>
char* find_substring(char* str1, char* str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);
int i, j;
for (i = 0; i <= len1 - len2; i++) {
for (j = 0; j < len2; j++) {
if (str1[i + j] != str2[j])
break;
}
if (j == len2)
return &str1[i];
}
return NULL;
}
int main() {
char str1[] = "hello world";
char str2[] = "world";
char* result = find_substring(str1, str2);
if (result != NULL)
printf("Substring found at address %p\n", result);
else
printf("Substring not found\n");
return 0;
}
```
程序首先计算str1和str2的长度。然后,它遍历str1中的每个字符,并在每个位置上尝试匹配str2。如果在某个位置上找到了匹配,它就返回该位置的地址。如果整个str1都被搜索完了,也没有找到匹配,就返回NULL。
相关推荐
![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)
![](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)