gpt4 book ai didi

c++ - 从 char 数组中删除重复的单词(仅在后面)

转载 作者:行者123 更新时间:2023-11-30 03:57:43 25 4
gpt4 key购买 nike

我有点卡住了,无法找出这里出了什么问题。我有一个任务是将一个句子输入到 char 数组中,如果有重复的单词和后面的单词(example :相同的相同,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;

}
}

最佳答案

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

关于c++ - 从 char 数组中删除重复的单词(仅在后面),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27815234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com