如何在字符串中查找重复的子串 用C语言编写
时间: 2024-02-16 19:59:54 浏览: 131
可以使用暴力枚举的方式来查找重复的子串,具体步骤如下:
1. 从字符串开头开始枚举每一个子串。
2. 对于每一个子串,将其与后面的所有子串进行比较,查看是否有相同的子串。
3. 如果找到相同的子串,则输出该子串,并记录其出现的位置。
以下是用C语言实现的代码示例:
```c
#include <stdio.h>
#include <string.h>
void findRepeatedSubstring(char *str) {
int len = strlen(str);
int i, j, k;
int maxLen = 0, maxStart = 0;
for (i = 0; i < len; i++) {
for (j = i + 1; j < len; j++) {
for (k = 0; k < len - j; k++) {
if (str[i+k] != str[j+k]) {
break;
}
}
if (k > maxLen) {
maxLen = k;
maxStart = i;
}
}
}
if (maxLen > 0) {
printf("Repeated substring: ");
for (i = 0; i < maxLen; i++) {
printf("%c", str[maxStart+i]);
}
printf("\n");
} else {
printf("No repeated substring found.\n");
}
}
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
findRepeatedSubstring(str);
return 0;
}
```
该程序首先读取一个字符串,并调用 `findRepeatedSubstring()` 函数来查找重复的子串。该函数通过三重循环来枚举每一个子串,并将其与后面的所有子串进行比较,找到最长的相同子串并输出。如果没有找到重复的子串,则输出相应的提示信息。
阅读全文
相关推荐















