【问题标题】:Checking both ends of a string not working检查字符串的两端不起作用
【发布时间】: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 的开头和结尾字符的最简单方法是使用 frontback 方法。不过,先进行测试以确保字符串不为空。
  • @JohnnyMopp word[word.size()] 在 C++11 及更高版本中有效,它返回对字符串空终止符的引用。

标签: c++ c++11


【解决方案1】:

如果字符串的大小为 4,那么只有 4 个元素:0、1、2 和 3。没有第五个元素,因此无法访问第四个元素。

如果一个字符串的长度是五:

零是第一个元素。
一是第二要素。
二是第三个要素。
三是第四元素。

第五个元素当然是Leeloo,它不是字符串中的一个字符。如果一个字符串的长度是四,你不应该尝试访问第五个元素(至少,没有她的许可)。

Ecto gamat。

【讨论】:

  • "没有第五个元素,所以你不能访问第四个元素。" - 实际上,在 C++11 及更高版本中,还有第五个元素,即 null终结者,您可以通过operator[]合法访问。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-05
  • 2019-06-06
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多