通过使用动态字符串简化了处理。
像这样
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct dstr {
size_t size;
size_t capacity;
char *str;
} Dstr;//dynamic string
Dstr *dstr_make(void){
Dstr *s;
s = (Dstr*)malloc(sizeof(Dstr));
s->size = 0;
s->capacity=16;
s->str=(char*)realloc(NULL, sizeof(char)*(s->capacity += 16));
return s;
}
void dstr_addchar(Dstr *ds, const char ch){
ds->str[ds->size] = ch;
if(++ds->size == ds->capacity)
ds->str=(char*)realloc(ds->str, sizeof(char)*(ds->capacity += 16));
}
void dstr_addstr(Dstr *ds, const char *s){
while(*s) dstr_addchar(ds, *s++);
//dstr_addchar(ds, '\0');
}
void dstr_free(Dstr *ds){
free(ds->str);
free(ds);
}
void dic_entry(char *dic[26], const char *source){
char *p, *backup, ch;
p = backup = strdup(source);
for(;NULL!=(p=strtok(p, " \t\n"));p=NULL){
if(*p == '$' && isupper(ch=*(p+1))){
if(dic[ch -'A'] == NULL)
dic[ch -'A'] = strdup(p+2);
}
}
free(backup);
}
void dic_clear(char *dic[26]){
int i;
for(i=0;i<26;++i){
if(dic[i]){
free(dic[i]);
dic[i] = NULL;
}
}
}
int main(void){
const char *template = "I have $A,$B,$C.";
char *dic[26] = { 0 };
char buff[1024];
const char *cp;
Dstr *ds = dstr_make();
printf("input special value setting: ");
fgets(buff, sizeof(buff), stdin);
dic_entry(dic, buff);
for(cp=template;*cp;++cp){
if(*cp == '$'){
char ch;
if(isupper(ch=*(cp+1)) && dic[ch - 'A']!=NULL){
dstr_addstr(ds, dic[ch - 'A']);
++cp;
} else {
dstr_addchar(ds, *cp);
}
} else {
dstr_addchar(ds, *cp);
}
}
dstr_addchar(ds, '\0');
printf("result:%s\n", ds->str);
dic_clear(dic);
dstr_free(ds);
return 0;
}
/* DEMO
>a
input special value setting: $ACar $BBike $CTruck
result:I have Car,Bike,Truck.
>a
input special value setting: $BBike
result:I have $A,Bike,$C.
*/