从字符数组中删除停用词
Removing stopwords from char array
>我正在尝试创建一个函数,从字符数组中删除预定义的单词(字符数组)。它有点工作并从 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);
}
}
请注意,此解决方案的代码大小非常高效,并且可能太聪明而无法作为第一年的程序员代码传递。我希望这对您在没有资格作为代码练习解决方案提交时学习有用:-)
相关文章:
- 正在从C++中的字符数组中删除字符
- 从字符串中删除字符
- 如果不是十六进制,则QT从qlineedit中删除字符
- 从长字符串中删除字符
- 从文件对象的当前位置删除字符
- C++ 删除字符**
- 从字符串中删除字符的第一个和最后一个实例
- 如何在C++中删除字符*数组
- 如何从C 中的字符串中删除字符
- 用“ strcpy”在2D数组中删除(字符)的一行(字符)时是否存在任何错误
- 删除字符并在字符串(C )的末端附加它们
- C++ 字符串,用于删除字符'b'并将字符'a'替换为两个'd'的构建函数
- 在字符串中的定界符之间删除字符
- 从 std::字符串中删除字符从 "(" 到 ")" 用擦除?
- 使用擦除和删除从字符串中删除字符
- C++ 如何删除字符中的双引号
- C++ 中的密码 |打印字符后删除字符
- C++在链表中插入和删除字符
- 字符串流的获取函数不删除字符
- 删除字符C++最后一次出现时字符数组的开头