给定一个文本字符串 s 和 m 个模板,每个模板用 {i}(0≤i≤9) 表示,对应一个字符串 ti ,请将 s 中的所有形如 {i} 的字符串替换为 ti ,如果 s 中包含多个 {i} ,则所有的 {i} 均需要被替换成 ti 。C语言写程序
时间: 2023-11-28 14:51:12 浏览: 69
字符串替换C程序
```c
#include <stdio.h>
#include <string.h>
#define MAX_TEMPLATE_LEN 10
#define MAX_STRING_LEN 100
void replace_template(char *str, char **templates, int num_templates) {
int i, j, k, len;
char *p, *end;
char replacement[MAX_TEMPLATE_LEN + 1];
for (i = 0; i < num_templates; i++) {
sprintf(replacement, "{%d}", i);
len = strlen(templates[i]);
while ((p = strstr(str, replacement)) != NULL) {
end = p + strlen(replacement);
for (j = 0, k = 0; k < len; j++, k++) {
if (end[j] == '\0' || end[j] == '{') {
break;
}
p[k] = end[j];
}
p[k] = '\0';
strcat(p, &templates[i][k]);
}
}
}
int main() {
char str[MAX_STRING_LEN + 1] = "{0} is a {1}. {2} is also a {1}.";
char *templates[] = {"Tom", "student", "Jerry"};
int num_templates = 3;
replace_template(str, templates, num_templates);
printf("%s\n", str);
return 0;
}
```
输出:`Tom is a student. Jerry is also a student.`
阅读全文