【发布时间】:2015-12-13 16:00:03
【问题描述】:
如何更改此代码以替换字符串中每个单词的出现,但不会替换所有子字符串。例如,如果单词是 ask,则不会替换 task 或 asking。因此,对于输入:“I'm ask a task ask my friend”和替换词:“for”输出应为:“I'm ask for a task for my friend”。
char *replace_word(char *string, char *word, char *new_word) {
int len = strlen(string) + 1;
char *temp = malloc(len * sizeof(char));
int temp_len = 0;
char *found;
int len_w = strlen(word);
while (found = strstr(string, word)) {
if ((isalnum(*(found - 1))) || (isalnum(*(found + len_w)))) {
break;
}
else {
memcpy(temp + temp_len, string, found - string);
temp_len = temp_len + found - string;
string = found + strlen(word);
len = len - strlen(word) + strlen(new_word);
temp = realloc(temp, len * sizeof(char));
memcpy(temp + temp_len, new_word, strlen(new_word));
temp_len = temp_len + strlen(new_word);
}
}
strcpy(temp + temp_len, string);
return temp;
}
在这个阶段,如果输入是:“它问我这个任务?”就可以了。输出是:“这个任务是给我的?”但是如果输入是这样的:“我问这个问朋友”,输出将与输入相同,因此代码不会进行更改。需要帮忙!
【问题讨论】: