我需要编写一个函数,该函数将从字符串中删除所有重复的子字符串,下面的函数比工作但不那么正确。
输入:这是对第 2 课的简单测试 退出第 2 课
输出:第2课的这个简单测试退出
如您所见,从句子中删除函数“ is ”,但它不正确。
void RemoveDuplicates(char text[], size_t text_size, char** output)
{
char *element;
/* Allocate size for output. */
*output = (char*) malloc(text_size);
*output[0] = '\0';
/* Split string into tokens */
element = strtok(text, " ");
if (element != NULL)
strcpy(*output, element);
while( (element = strtok(NULL, " ")) != NULL ) {
/* Is the element already in the result string? */
if (strstr(*output, element) == NULL) {
strcat(*output, " " );
strcat(*output, element );
}
}
}
更新版本的代码 (@Rohan)
输入:这是一个简单的测试,对于第 2 课来说很简单退出
输出:这是一个简单的测试,对于第 2 课退出
void RemoveDuplicates(char text[], size_t text_size, char** output)
{
char *temp = NULL;
char *element;
/* Allocate size for output. */
*output = (char*) malloc(text_size);
*output[0] = '\0';
/* Split string into tokens */
element = strtok(text, " ");
if (element != NULL)
strcpy(*output, element);
while( (element = strtok(NULL, " ")) != NULL ) {
/* Is the element already in the result string? */
temp = strstr(*output, element);
/* check for space before/after it or '\0' after it. */
if (temp == NULL || temp[-1] == ' ' || temp[strlen(element)] == ' ' || temp[strlen(element)] == '\0' ) {
strcat(*output, " " );
strcat(*output, element );
}
}
}