【问题标题】:How do I cout string array in this way我如何以这种方式计算字符串数组
【发布时间】:2019-12-11 17:14:27
【问题描述】:

所以我决定检查这个词是否是回文。所以我做了2个字符串,我必须输入单词(比如"Hello")。我不明白如何比较这2个字符串,而且我在使用word.length和变量i时出错。我如何解决它?是否有必要更改代码或者我可以更改我的某些内容?

string word,s;
cin>>word;
for(int i=word.length()-1;i>=0;i--){
    s[i]=word[i];
}
if(s==word)
    cout<<1;

【问题讨论】:

  • s[i]=word[i]; 是未定义的行为,因为 s 为空。
  • 您的标题似乎与问题无关
  • 当您寻求帮助修复编译器错误时,您应该在问题中包含错误消息
  • 如果你说I have an error 这没有帮助,因为据我们所知,错误可能是你试图用 Java 编译器而不是 c++ 编译器来编译它,或者试图在 Sony Vegas Pro 中打开这个程序.请把错误放在问题正文中。
  • 这里是错误。隐式转换失去整数精度:'std::__1::basic_string, std::__1::allocator >::size_type'(又名'unsigned long')到'int'

标签: c++ arrays string palindrome


【解决方案1】:

事实上,没有必要使用额外的字符串来检查给定的字符串是否是回文。您可以循环执行这样的检查。

但是,使用您的方法,您可以编写得更简单。例如

if ( word == std::string( word.rbegin(), word.rend() ) ) std::cout << 1; 

至于您所说的错误,当您将有符号整数 i 与调用 word.length*() 返回的无符号整数值进行比较时,编译器似乎不喜欢。

此外,由于字符串 s 为空,因此您不能使用下标运算符

s[i]=word[i];

你也可以写

s += word[i];

s.push_back( word[i] );

初步你可以为字符串 s like 预留足够的内存

s.reserve( word.size() );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    相关资源
    最近更新 更多