请写出查找子串的c语言程序
时间: 2023-03-13 15:12:10 浏览: 96
int search_substring(char str[], char sub[])
{
int c, d, e, sublen; sublen = strlen(sub); for (c = 0; str[c] != '\0'; c++) {
if (str[c] == sub[0]) {
for (d = 0; d < sublen; d++) {
if (str[c+d] == sub[d])
e++;
}
if (e == sublen)
return c;
}
}
return -1;
}
相关问题
用C语言写一个程序查找子串并实现子串的替换操作,并写出具体思路
好的,下面是用C语言实现查找子串并替换的思路:
1. 首先定义一个函数,用于查找主串中的子串,并返回子串在主串中的位置(如果存在)。
2. 如果子串存在,则定义另外一个函数用于替换操作。这个函数需要接受三个参数:主串、子串和替换的字符串。
3. 在这个函数中,我们需要先计算出替换后的字符串的长度,然后申请一个新的字符串空间,将替换后的字符串复制到新的字符串空间中。
4. 然后开始遍历主串,如果发现子串,就将替换后的字符串复制到新的字符串空间中,并将指针移动到替换后的字符串的结尾处。
5. 如果没有发现子串,就将主串当前位置的字符复制到新的字符串空间中,并将指针移动到新的字符串空间中的下一个位置。
6. 最后,将新的字符串空间中的内容复制回原来的主串中,完成替换操作。
下面是一个实现查找子串并替换的示例函数:
```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int find_substring(char *str, char *sub)
{
int len1 = strlen(str);
int len2 = strlen(sub);
int i, j;
for(i = 0; i <= len1 - len2; i++)
{
for(j = 0; j < len2; j++)
{
if(str[i+j] != sub[j])
break;
}
if(j == len2)
return i;
}
return -1;
}
void replace_substring(char *str, char *sub, char *replace)
{
int len1 = strlen(str);
int len2 = strlen(sub);
int len3 = strlen(replace);
char *new_str = (char *) malloc(len1 * len3 * sizeof(char));
int i = 0, j = 0;
while(str[i] != '\0')
{
if(find_substring(&str[i], sub) == 0)
{
strcpy(&new_str[j], replace);
j += len3;
i += len2;
}
else
{
new_str[j] = str[i];
i++;
j++;
}
}
new_str[j] = '\0';
strcpy(str, new_str);
free(new_str);
}
int main()
{
char str[100] = "hello world, world is beautiful!";
char sub[10] = "world";
char replace[20] = "universe";
printf("Before replace: %s\n", str);
replace_substring(str, sub, replace);
printf("After replace: %s\n", str);
return 0;
}
```
这个程序先定义了一个 `find_substring()` 函数用于查找子串,如果找到,则返回子串在主串中的位置。然后定义了一个 `replace_substring()` 函数用于替换操作。这个函数先计算出替换后的字符串的长度,然后申请一个新的字符串空间,遍历主串,如果发现子串,则将替换后的字符串复制到新的字符串空间中。最后将新的字符串空间中的内容复制回原来的主串中,完成替换操作。
在 `main()` 函数中,我们定义了一个主串、一个子串和一个替换字符串,然后调用 `replace_substring()` 函数进行替换操作。
C语言写字符串查找程序
### C语言实现字符串查找程序示例
在C语言中,可以利用标准库中的`<string.h>`头文件所提供的函数来进行字符串操作。对于字符串查找的需求,有多种方法可供选择。
#### 使用 `strstr` 函数进行子串匹配
`strstr` 是一种简单而有效的方法来检测一个字符串是否存在于另一个字符串之中。该函数返回指向首次出现的子串位置的指针;如果未找到,则返回NULL[^1]。
```c
#include <stdio.h>
#include <string.h>
int main() {
const char source[] = "This is a test string.";
const char target[] = "test";
// 调用 strstr 来查找目标字符串
char *result = strstr(source, target);
if (result != NULL) {
printf("Found substring at position %ld\n", result - source);
} else {
printf("Substring not found.\n");
}
return 0;
}
```
此代码片段展示了如何通过调用`strstr`函数并传入源字符串和待查的目标字符串完成基本的字符串查找任务。当找到了匹配项时,会打印出其相对于原字符串起始地址的位置偏移量[^2]。
另外,在实际应用中可能还需要考虑大小写敏感性等问题,此时可以根据具体需求调整算法逻辑或选用其他更复杂的解决方案[^3]。
阅读全文
相关推荐
















