在字符数组中选择一个字并逐个比较
假设我有一个字符数组,其中包含重复字词,我将删除它而不使用字符串字典库但仅限于cstring库。在字符数组中选择一个字并逐个比较
*****示例文本******
一个一个一个的中短篇小说体裁最有名的标题是必读的。这个故事讲述的是一对年轻夫妇以及他们如何应对购买圣诞节礼物的挑战,当他们没有足够的钱时钱钱。
*****该编辑的文本******
其中最有名的标题中短篇小说体裁是一个必须阅读。这个故事讲述的是一对年轻夫妇,以及他们如何应对购买圣诞节礼物的挑战,当他们没有足够的钱时钱。
我已经将文本存储到一个char数组并将文本转换为大写字母。
char str[100];
但我怎么才能得到这个词,并逐一比较它们?其中一些甚至包含标点符号。像“钱钱”。它也是重复的。
我认为你不能使用分隔符函数,因为你想保留空格和标点符号。我有一个解决您的问题,我认为你可以从代码中得到一个想法。
#include <iostream>
#include <cstring>
using namespace std;
#define MAX_ITEM_LENGTH 20
#define MAX_ITEM_COUNT 200
#define MAX_STRING_LENGTH 1000
char delimeters[] = {' ', ',', '.', '-'};
bool equals(char* str1, char* str2, int length1, int length2){
if(length1 != length2)
return false;
for(int i = 0; i < length1; i++)
if(toupper(str1[i]) == toupper(str2[i]))
return true;
return false;
}
int parse(char* str, char*** result){
int index = 0;
int totalCount = 0;
for(; totalCount < MAX_ITEM_COUNT && str[index] != '\0' ; totalCount++){
for (int resultIndex = 0 ; resultIndex < MAX_ITEM_LENGTH; resultIndex++){
if (resultIndex > 0 && strchr(delimeters,str[index])){
break;
}
(*result)[totalCount][resultIndex] = str[index];
index++;
if(strchr(delimeters, str[index-1]))
break;
}
}
return totalCount;
}
int removeDuplicates(char** items, int itemsLength, char*** result){
char* lastItem = new char[MAX_ITEM_LENGTH];
int index = 0;
for(int i = 0 ; i < itemsLength ; i++){
if(equals(items[i], lastItem, strlen(items[i]), strlen(lastItem))){
index--;
continue;
}
strcpy((*result)[index++], items[i]);
if(!strchr(delimeters, items[i][0])){
strcpy(lastItem, items[i]);
}
}
return index;
}
int main() {
char str[MAX_STRING_LENGTH] = "One one one of the most famous titles in the short story genre is a must-read. The story is about a young couple and how they meet the challenge of buying each other a Christmas gifts when they don't have enough money money money.";
char** items;
char** result;
items = new char*[MAX_ITEM_COUNT];
result = new char*[MAX_ITEM_COUNT];
for(int i = 0; i < MAX_ITEM_COUNT; i++){
items[i] = new char[MAX_ITEM_LENGTH];
result[i] = new char[MAX_ITEM_LENGTH];
}
int itemsLength = parse(str, &items);
int resultLength = removeDuplicates(items, itemsLength, &result);
for(int i = 0; i < resultLength; i++)
cout<<result[i];
return 0;
}
谢谢cokceken,但我对你的代码并不熟悉。在解析()中,为什么 “if(strchr(delimeters,str [index-1]))break;”需要申请? – Harry2046
如果str [index-1](例如','字符)存在于delimeters字符串中(在我们的例子中为true),则strchr返回一个非零数字。如果我们有像“数组”这样的字符串,我们需要停在','并且不要将它包含在单词中。通过这个控制,我们将“array”解析为{“array”,“,”} not {“array,”} – cokceken
再次感谢您。但是,我发现了一些有线的东西。有时你怎么使用(* result)[totalCount] [resultIndex] = str [index];有时你使用strcpy((* result)[index ++],items [i]); ? – Harry2046
如果您只想使用C类型和C函数,为什么要标记'C++'?并使用['strpbrk'](http://www.cplusplus.com/reference/cstring/strpbrk/)查找单词分隔符和['strstr'](http://www.cplusplus.com/reference/cstring/ strstr /)查找char中的识别字 – Garf365