【问题标题】:Why are these strings not equal? are they the same?为什么这些字符串不相等?他们是一样的吗?
【发布时间】:2023-01-08 18:08:41
【问题描述】:

正在做一些 leet 代码,我想知道这两个字符串比较如何抛出错误,尝试以其他方式比较它们但没有成功。

    
int main(){
    
    std::cout<<std::boolalpha;
    std::string sa{"A man, a plan, a canal: Panama"};** // was trying to check if this was palindrome**

    for (int i{}; i < sa.size(); i++) { 

        if (!isalnum(sa[i]))//**removing non alpha chars
            sa[i] = '\0';**
        else sa[i] = tolower(sa[i]);
    }
    std::string se = sa;
    std::reverse(se.begin(), se.end());
    std::cout << (se == sa); **//turns out both strings are the same but this throws false **to the console

    return 0;
}

【问题讨论】:

  • 字符串根本不一样。您用 \0 替换了所有非字母数字字符。这将如何使字符串等于它的反转?
  • 字符串不一样——你试过把它们打印出来吗?

标签: c++ string


【解决方案1】:

'替换非字母数字字符

猜你喜欢
  • 1970-01-01
  • 2021-12-23
相关资源
最近更新 更多