gpt4 book ai didi

c++ - 字符串比较 - 替换字符数组中的单词

转载 作者:太空宇宙 更新时间:2023-11-04 11:30:14 25 4
gpt4 key购买 nike

我正在编写一个函数,它接受一个包含书名的字符数组作为参数,然后必须执行以下操作:

  1. 需要删除单词之间的多余空格[完成]**

  2. 文本必须转换为首字母大写,即每个新词必须以大写字母开头 [DONE]

  3. 最后,我有一个文本文件 (minors.txt),其中包含一些不应被函数大写的单词,例如“a”和“一个”,但是我不知道如何实现这个,关于如何实现的任何帮助这样做将不胜感激!

示例:

ENTER THE TITLE OF THE BOOK: a brief hisTOry OF everyTHING

正确的输出:

a Brief History of Everything

这是我的代码:

bool Book :: convertToTitleCase(char* inTitle)
{
int length = strlen(inTitle);
bool thisWordCapped = false;

//Convert paramater to lower case and
//Remove multiple white spaces
for (int x = 0; x < length; x++)
{
inTitle[x] = tolower(inTitle[x]);

if (isspace(inTitle[x]) && isspace(inTitle[x+1]))
{
while (isspace(inTitle[x]) && isspace(inTitle[x+1]))
{
int i;
for (i = x + 1; i < length; i++)
{
if(i==(length-1))
{
inTitle[i] = '\0';
}
else
{
inTitle[i] = inTitle[i+1];
}
}
}
}
}

/* Read through text file and identify the words that should not be capitalized,
dont know how, please help! */

//Capitalize the first letter of each word
for (int i = 0; i < length; i++)
{
if ((ispunct(inTitle[i])) || (isspace(inTitle[i])))
{
thisWordCapped = false;
}

if ((thisWordCapped==false) && (isalpha(inTitle[i])))
{
inTitle[i] = toupper(inTitle[i]);
thisWordCapped = true;
}
}
return true;

我正在考虑将文本文件中的单词读入一个字符串数组,然后比较这两个数组以确保当文本文件中出现一个单词时,该单词没有大写,但是我没有知道在字符串数组和字符数组之间是否可行。

我完全不知道该做什么或它是如何工作的,任何帮助将不胜感激,谢谢!

PS - 我对 C++ 还是比较陌生,所以请原谅低效的代码,

最佳答案

最好将文件读入 setunordered_set,而不是数组 - 类似于:

std::set<std::string> words;
if (std::ifstream in("minors.txt"))
{
std::string word;
while (in >> word)
words.insert(word);
}
else
{
std::cerr << "error reading minors.txt file\n";
exit(EXIT_FAILURE);
}

在程序开始时执行一次,然后在将单词大写之前使用 words.count(the_word) 查看它是否需要大写。

关于c++ - 字符串比较 - 替换字符数组中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25058507/

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