【发布时间】:2020-08-25 01:17:06
【问题描述】:
我正在尝试字符串的开头和结尾。如果单词有大写字母,我们将其更改为小写。如果单词有空格或'"',我们会删除该字符。第一次递归调用它应该检查并看到字符串的末尾有一个大写字母,它应该将其更改为小写。但是,当我输出word[word.size()] 时,它会输出一个空格,但我输出word[word.size() - 1] 它会输出我正在寻找的字母。我不确定空格是什么以及我应该如何处理它,因为我不希望它出现在我的字符串中,因为它会导致比较问题。
bool checkPalindrome(string word){
if (isupper(word[0]))
{
word[0] = tolower(word[0]);
}
if (isupper(word[word.size()]))
{
word[word.size()] = tolower(word[word.size()]);
}
//check if there is a space or "" if there is then delete that position from the string
if (word[0] == ' ' || word[0] == '"')
{
word.erase(1);
}
if (word[word.size()] == ' ' || word[word.size()] == '"')
{
word.pop_back();
}
if (word.size() > 1)
{
if (word[0] == word[word.size()])
{
word = word.substr(1, word.size() - 2);
return checkPalindrome(word, count);
}
else
{
return false;
}
}
else
{
return false;
}
int main()
{
ifstream inFile;
bool check = false;
string temp = "";
int count = 0;
vector<string> vect;
//Reading from a file line by line
inFile.open("words.txt");
if (inFile.is_open())
{
while (getline(inFile, temp))
{
vect.push_back(temp);
}
}
inFile.close();
for (auto i = 0; i < vect.size(); i++)
{
count = vect[i].size();
check = checkPalindrome(vect[1], count);
if (check == true)
{
cout << vect[i] << ", is a palindrome!\n";
}
else
{
cout << vect[i] << ", is not a palindrome.\n";
}
}
} return 0;
【问题讨论】:
-
请提供minimal reproducible example。在这种情况下,您可以硬编码
words.txt的内容。 -
word[word.size()]是最后一个字母之后的一个。有效索引为[0 to size-1]。 -
从 C++11 开始,获取
string的开头和结尾字符的最简单方法是使用front和back方法。不过,先进行测试以确保字符串不为空。 -
@JohnnyMopp
word[word.size()]在 C++11 及更高版本中有效,它返回对字符串空终止符的引用。