问题描述
我正在研究从文本文件读取,将单词更改为小写,删除标点符号并检查单词是否有效然后存储到二进制搜索树中的二进制搜索树。
在这里,我创建了一个名为isValidWord()
的函数,该函数检查单词是否为小写字母,是否包含任何数字以及是否包含标点符号。但是出于某种原因,它仍然允许将无效的单词存储到二进制搜索树中。
isValidWord()函数
bool BST::isValidWord(string word) {
for (int i = 0; word.size(); i++)
{
if (!isalnum(word[i]))
{
if (!isdigit(word[i])) {
if (!ispunct(word[i])) {
if (!isupper(word[i])) {
return true;
}
}
}
}
}
return false;
}
BST插入功能
void BST::insert(string word,TreeNode*& root) {
transform(word.begin(),word.end(),word.begin(),::tolower);
for (int i = 0,len = word.size(); i < len; i++) {
if (ispunct(word[i])) {
word.erase(i--,1);
len = word.size();
}
}
if (isValidWord(word)) {
if (root == NULL) {
root = new TreeNode(word);
}
else if (root->data == word) {
root->count++;
}
else {
if (word >= root->data) {
insert(word,root->right);
}
if (word <= root->data) {
insert(word,root->left);
}
}
}
}
我在做错什么我看不到的东西吗?任何帮助将不胜感激。
解决方法
我看不到for循环中的中断条件。
for (int i = 0; word.size(); i++)
{
应将其替换为
for (int i = 0; i < word.size(); i++)
{
,
该问题要求使用std::regex
。
可以用一个非常简单的单行代码代替整个“ isValidWord”函数:
if (std::regex_match(word,std::regex("[a-z]+"))) {
在方括号中,您可以指定所有有效字符。例如[a-z]表示所有小写字符。
也是你的台词
for (int i = 0,len = word.size(); i < len; i++) {
if (ispunct(word[i])) {
word.erase(i--,1);
len = word.size();
}
}
可以简单地用超简单的一根衬纸代替:
word = std::regex_replace(word,std::regex(R"([\.,:])"),"");
将要删除的内容放在括号中。
请考虑。
如果您有任何疑问,请询问