从字符数组中删除停用词

Removing stopwords from char array

本文关键字:删除 字符 数组      更新时间:2023-10-16

>我正在尝试创建一个函数,从字符数组中删除预定义的单词(字符数组)。它有点工作并从 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] != ''; i++) {
        if (str[i] == ' ') {
            str1[k][j] = '';
            k++;
            j = 0;
        }
        else {
            str1[k][j] = str[i];
            j++;
        }
    }
    str1[k][j] = '';
    /* 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]);
    }
}

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

像这样开始:

将初始字符串与键进行比较,num = 键的长度。

如果匹配,则删除子字符串

将一个字符移动到初始字符串中,然后再次比较。

循环,直到初始字符串中剩余的字符少于键的长度。

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

替换代码中的上述函数。

我会选择可读的算法。

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);
    }
}

请注意,此解决方案的代码大小非常高效,并且可能太聪明而无法作为第一年的程序员代码传递。我希望这对您在没有资格作为代码练习解决方案提交时学习有用:-)