从char数组中删除停用词

时间:2016-02-19 12:09:45

标签: c++ arrays word

我试图创建一个从char数组中删除预定义单词(char数组)的函数。它有点工作并从char数组中删除单词,但它只有在单词用空格分隔时才有效。我想这样做是为了从一组没有空格分隔的单词中删除单词,但我不知道如何。我坚持这一点,并希望得到任何帮助。

int i, j = 0, k = 0, count = 0;
char str[1024] = "thisisthestringtobealtered."; // works using spaces
char key[256] = "the"; // I want "the" to be removed in str
char str1[10][20];

void removeWordFromString(){

    /* Converts the string into 2D array */
    for (i = 0; str[i] != '\0'; i++) {
        if (str[i] == ' ') {
            str1[k][j] = '\0';
            k++;
            j = 0;
        }
        else {
            str1[k][j] = str[i];
            j++;
        }
    }
    str1[k][j] = '\0';

    /* Compares the string with given word */
    for (i = 0; i < k + 1; i++) {
        if (strcmp(str1[i], key) == 0) {
            for (j = i; j < k + 1; j++)
                strcpy(str1[j], str1[j + 1]);
            k--;
        }

    }


    for (i = 0; i < k + 1; i++) {
        printf("%s ", str1[i]);
    }

}

3 个答案:

答案 0 :(得分:0)

此问题的可能解决方案是使用strncmp()。 此功能允许您比较子字符串。

像这样开始:

将初始字符串与密钥进行比较,其中num =密钥的长度。

如果确实匹配则将子串切掉

将一个字符移动到初始字符串中并再次进行比较。

循环,直到你的初始字符串中的字符少于你的密钥很长。

答案 1 :(得分:0)

void removeWordFromString(){    
        /* Converts the string into 2D array */
        int ckey=0;
        i=0;
        while(str[i] != '\0')
        {
                while(str[i] == key[ckey] && key[ckey] != '\0')
                {
                        str1[k][j] = str[i];
                        j++;
                        i++;
                        ckey++;
                }
                if ( key[ckey] == '\0' )
                {
                        str1[k][j-strlen(key)] = '\0';
                        k++;
                        j = 0;
                        ckey=0;
                }
                else{
                        str1[k][j] = str[i];
                        j++;
                        i++;
                        ckey=0;
                }
        }
        str1[k][j] = '\0';

        for (i = 0; i < k + 1; i++) {
                    printf("%s ", str1[i]);
        }
}

替换代码中的上述功能。

答案 2 :(得分:0)

我会选择一种可读的算法。

Find the place in the string where the key occurs.
while I can find such a place, then 
    remove this occurrence
    look for the next.

或代码:

char str[1024] = "thisisthestringtobealtered."; // works using spaces
char key[256] = "the"; // I want "the" to be removed in str

void removeWordFromString(){
    char* p = strstr(str, key);
    while (p) {
        // Move from end of key, to start of key, the number of characters we can 
        // find after the key, plus a null terminator. Memmove because the string 
        // overlaps itself.
        memmove(p, p + strlen(key), strlen(p) - strlen(key) + 1);
        p = strstr(str, key);
    }
}

请注意,此解决方案的代码大小非常高,并且可能太聪明,不能作为第一年的程序员代码传递。我希望这对你来说有用,因为你没有资格作为代码练习解决方案进行学习: - )

相关问题