问题描述
output = array[0:-1][array[1:]-array[0:-1] != 1]
}
实际上,我想确定给定的字符串是否是回文,所以我将第一个字符串以相反的顺序存储在第二个字符串中,然后最终检查它们是否相等,但是我无法甚至可以打印出临时字符串的结果
解决方法
您定义了一个std :: string类型的空对象
string temp;
因此,不得在循环中将下标运算符与空对象一起使用。
int k = 0;
for(int i = length-1; i>=0; i--){
temp[++k] = str[i];
}
使用您的方法,您可以编写
string temp( str.rbegin(),str.rend() );
不使用循环。
但是,如果要检查字符串是否是回文,则无需创建中间字符串。
您可以按以下方式循环进行操作。
std::string::size_type i = 0;
for ( auto n = str.length(); i < n / 2 && str[i] == str[n - i - 1]; )
{
++i;
}
if ( i == str.length() /2 ) std::cout << str << " is a palindrome\n";
或者没有循环而又定义了一个可以写的变量
if ( str == std::string( str.rbegin(),str.rend() ) )
{
std::cout << str << " is a palindrome\n";
}