其他人评论了您描述问题的糟糕程度,并向您抛出了您可能不理解的复杂的基于模板的代码。我强烈建议您阅读它;模板功能强大、有用,而且是一种很棒的编程技术。缺点是你必须先学习它们。
这是一个非面向模板的解决方案:
bool class3::filter(string word)
{
//You aren't mutating word, so don't waste your time
//(or memory) by copying it. In fact, I'd (strongly)
//recommend you utilize a constant pass by reference,
//because by default that's what you're already doing,
//so you were taking a copy of a copy. Waste of memory!
//Just init a count variable.
int count=0;
//Set up your for loop...
for(int i=0; i<word.size(); i++)
{
if(!isalnum(word[i]))
{
//If a character doesn't match, increment your counter
count++;
//If you want to, you can return false here if count>1 to improve efficiency -- depends on your end goal.
}
}
//If you want exactly one non-alphanumeric, then return this.
return count==1;
//Or if it's a maximum of one non-alphanumeric, then...
return count<=1;
//Or you could generalize by returning a count of non alphanumerics -- remember to change the return type!
return count;
}