所以,我必须用更大的字符串替换每个单词的出现,并且我有一个函数来执行此操作,如下所示:
void replace(char *sir, char *word1, char *word2) {
char *buffer;
buffer = calloc(LMAX, sizeof(char));
char *insert_point = &buffer[0];
char *tmp = sir;
int l1 = strlen(word1);
int l2 = strlen(word2);
while (1) {
char *p = strstr(tmp, word1);
if (p == NULL) {
strcpy( insert_point, tmp );
break;
}
memcpy(insert_point, tmp, p - tmp);
insert_point += p - tmp;
memcpy(insert_point, word2, l2);
insert_point += l2;
tmp = p + l1;
}
strcpy(sir, buffer);
free(buffer);
}
哪个有效,但它也取代了子串,而不仅仅是单词。例如,如果我有:"这是我的字符串"我想取代'与西瓜'我会得到这样的东西:"这是我的西瓜西瓜"。 所以,我的问题是如何让我的程序检查他的替换是否是一个单词?
答案 0 :(得分:2)
您需要检查要替换的单词之前和之后是否有空格。有特殊条件:
我在你的代码中添加了这个逻辑:
void replace(char *sir, char *word1, char *word2)
{
char *buffer;
buffer = calloc( 100, sizeof(char) );
char *insert_point = &buffer[0];
char *tmp = sir;
int l1 = strlen( word1 );
int l2 = strlen( word2 );
while(1)
{
char *p = strstr( tmp, word1 );
if( p == NULL )
{
strcpy( insert_point, tmp );
break;
}
memcpy( insert_point, tmp, p-tmp );
insert_point += p-tmp;
if ( (p == sir || isspace((unsigned char)p[-1])) &&
(isspace((unsigned char)p[l1]) || p[l1] == 0) ) {
memcpy( insert_point, word2, l2 );
insert_point += l2;
}
else {
memcpy(insert_point, word1, l1);
insert_point += l1;
}
tmp = p+l1;
}
strcpy( sir, buffer );
free( buffer );
}