C语言:样例: 执行文件 ./td6 abcabcbcakkbc bc lm 输出: bc 出现4次,位置信息为:2,5,7,11 替换后结果:almalmlmakklm
时间: 2024-05-05 15:21:41 浏览: 7
这是一个字符串匹配和替换的问题,下面是一个 C 语言的实现代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
void find_match(char *pattern, char *text, int *pos, int *count) {
int m = strlen(pattern);
int n = strlen(text);
int j, k;
*count = 0;
for (int i = 0; i <= n - m; i++) {
for (j = 0, k = i; j < m; j++, k++) {
if (text[k] != pattern[j]) break;
}
if (j == m) {
pos[*count] = i;
(*count)++;
}
}
}
void replace(char *text, int *pos, int count, char *new_text) {
int n = strlen(text);
int m = strlen(new_text);
int i, j, k;
for (i = n - 1; i >= 0; i--) {
text[i + (m - 1) * count] = text[i];
for (j = 0; j < count; j++) {
if (i == pos[j]) {
for (k = 0; k < m; k++) {
text[i + k + j * (m - 1)] = new_text[k];
}
}
}
}
}
int main() {
char text[MAX_LEN];
char pattern[MAX_LEN];
char new_text[MAX_LEN];
int pos[MAX_LEN];
int count;
printf("Enter text: ");
scanf("%s", text);
printf("Enter pattern: ");
scanf("%s", pattern);
printf("Enter new text: ");
scanf("%s", new_text);
find_match(pattern, text, pos, &count);
printf("%s appears %d times, at positions: ", pattern, count);
for (int i = 0; i < count; i++) {
printf("%d ", pos[i]);
}
printf("\n");
replace(text, pos, count, new_text);
printf("After replacement: %s\n", text);
return 0;
}
```
这个程序中,我们首先通过 `find_match` 函数找到字符串 `pattern` 在字符串 `text` 中出现的位置,然后通过 `replace` 函数将这些位置的字符串替换为新的字符串 `new_text`。