从char数组中删除重复的单词(仅在遵循时)

时间:2015-01-07 08:30:09

标签: c++ arrays char duplicates

我有点卡住,不知道这里有什么问题。 我有一个赋值给char数组输入一个句子,如果有重复和跟随的单词(示例:相同,diff diff。但不是:相同的单词相同。)他们应该被删除。 这是我写的函数:

void Same(char arr[], char temp[]){
    int i = 0, j = 0, f = 0, *p, k = 0, counter = 0;
    for (i = 0; i < strlen(arr); i++){
        while (arr[i] != ' ' && i < strlen(arr)){
            temp[k] = arr[i];
            i++;
            k++;
            counter++;
        }
        temp[k] = '\0';
        k = 0;
        p = strstr((arr + i), (temp + j));
        if (p != NULL && (*p == arr[i])){
            for (f = 0; f < strlen(p); f++){
                *p = '*';
                p++;
            }
            f = 0;
        }
        j = counter;

    }
}

1 个答案:

答案 0 :(得分:2)

strtok是一个方便的功能,可以从列表中获取下一个单词(strsep是一个更好的单词,但不太可能在您的系统上可用)。使用strtok,类似以下的方法可能会起作用,至少对于简单的示例......

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXPHRASELEN 1000
#define MAXTOKLEN 100

int main(int argc, char ** argv) 
{
    // Here is the sentence we are looking at
    char * tmp = "This is a test and and another test";
    // We will copy it to this variable
    char phrase[MAXPHRASELEN+1];
    strcpy(phrase, tmp);
    // And will put the altered text in this variable
    char new_phrase[MAXPHRASELEN+1];
    // This will be the last word we looked at
    char * lasttok = malloc(MAXTOKLEN+1);
    // This will be the current word
    char * tok = malloc(MAXTOKLEN+1);
    // Both words are initially empty
    new_phrase[0] = '\0';
    lasttok[0] = '\0';
    // Get the first word
    lasttok = strtok(phrase, " ");
    // If there is a word...
    if (lasttok != NULL) {
        // Put it in the altered text and add a space 
        strcat(new_phrase, lasttok);
        strcat(new_phrase, " ");
        // As long as there is a next word
        while ( (tok = strtok(NULL, " ")) != NULL ) {
            // See if it is the same as the last word
            if (strcmp(tok,lasttok) != 0) {
                // If it isn't, copy it to the altered text
                strcat(new_phrase, tok);
                // and add a space
                strcat(new_phrase, " ");
                // The current word becomes the last word
                lasttok = tok;
            }
        }
    }
    // Print the lot
    printf("%s\n", new_phrase);
}

如果你真的必须编写自己的例程来抓取单个单词,那么你可能会比模仿strtok更糟糕。它维护一个指向字符串中当前单词开头的指针,并在下一个分隔符(空格字符)中放置一个空字符。再次调用时,它只是将指针移动到经过null的字符,并在下一个分隔符后面放置另一个null。大多数字符串函数在传递指针时都会将null视为字符串的结尾,因此只需处理当前的单词。

减去评论,标题和初始化,它看起来不那么具威胁......

    lasttok = strtok(phrase, " ");
    if (lasttok != NULL) {
        strcat(new_phrase, lasttok);
        strcat(new_phrase, " ");
        while ( (tok = strtok(NULL, " ")) != NULL ) {
            if (strcmp(tok,lasttok) != 0) {
                strcat(new_phrase, tok);
                strcat(new_phrase, " ");
                lasttok = tok;
            }
        }
    }
    printf("%s\n", new_phrase);