I need to write a function which will remove all duplicates sub-strings from the string, the function below do than job but not so correct.
Input: This is a simple test for lesson2 Quit lesson2
Output: This simple test for lesson2 Quit
As you can see function remove "is" from the sentence but it is not correct.
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 );
}
}
}
Updated Version of Code (@Rohan)
Input: This is a is is simple test simple for lesson2 Quit
Output: This is a is is simple test simple for lesson2 Quit
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 );
}
}
}