c - delete repeated following words in an array
问题描述
I got assignment to check string and to see if there is repeated words inside it
for example Source string: this is is a test test.
changes to: this is a test.
void RemoveDuplicates(char *fixst) {
char tempstr[N];
char *subst = NULL;
*tempstr = 0;
subst = strtok(fixst, " ");
if ((subst != NULL) && strstr(tempstr, subst) == NULL)
{
strcpy(tempstr, subst);
while ((subst = strtok(NULL, " ")) != NULL)
{
if (strstr(tempstr, subst) == NULL)
{
strcat(tempstr, " ");
strcat(tempstr, subst);
}
}
}
strcpy(fixst, tempstr);
}
This is my code and the output that i'm getting is: this a test
As you can see the word 'is' deleted.
Another String: this is a test test to to this class.
Changes to: this a test to class.
Expected output: this is a test to this class.
Also delete the word 'is' and 'this'.
Any suggestions?
解决方案
下面的简单算法迭代输入字符数组中的每个标记/单词。当它找到一个新的标记/单词时,它将把它复制到输出字符串,如果:
- 它是第一个令牌,或者
- 它与最后一个令牌不同
在循环的每次迭代中都会更新指向前一个标记的指针 - 以便于比较。
void remove_duplicate_words(char *input) {
size_t input_len = strlen(input);
char *result = (char *)malloc(input_len + 1);
if (!result) {
fprintf(stderr, "Memory allocation failed!");
return;
}
char *last_word = NULL;
char *word = strtok(input, " ");
while (word) {
// Is this either the first word or different from the last word?
if (last_word == NULL || strcmp(word, last_word) != 0) {
// Yes -> append it to the output array
strcat(result, word);
strcat(result, " ");
}
last_word = word;
word = strtok(NULL, " ");
}
puts(result);
free(result);
}
笔记:
- 我在您的示例中使用了不同的变量名称 - 选择了我认为更清楚地传达其含义的变量名称。
- 输出数组 ( ) 的内存
result
是根据输入字符串的长度动态分配的。(我们知道它不能长于输入数组)。
推荐阅读
- reactjs - IE 11 中的 react-sortable-hoc 问题
- python - 如何使用自定义数据集进行 PyTorch/few-shot-vid2vid 训练
- installation - 解决 bizapps-dev-box 的 readlink 问题
- python-3.x - 使用 python Pandas 将文本文件导出到 excel
- docker - 如何在 Windows 10 中通过 Visual Studio Code 打开在 Docker 容器中克隆的存储库?
- vim - YcmCompleter GoToDefinitionElseDeclaration 的快捷方式不起作用
- node.js - 如何在 post 路由上模拟 Express/Node.js 中间件?
- python - 使用下载 api 请求对视图进行 CSRF 保护
- angular - 如何为 Flask-Angular 应用程序生成 docker 文件?
- php - 如何在 Laravel 中显示父级名称