问题描述
我正在codewars.com上执行练习任务,我已经完成了代码并对其进行了测试。它起作用了,所以我尝试上交它,但是随后抛出了2种情况,我的代码不起作用。我想纠正错误,但我不明白错误/尝试失败的含义。
这是错误消息:
Sample_Test_Cases
Caught std::exception,what(): basic_string::substr: __pos (which is 18446744073709551615) > this->size() (which is 3)
Random_Test_Cases
Caught std::exception,what(): basic_string::substr: __pos (which is 18446744073709551614) > this->size() (which is 8)
如果这完全有问题,这是我的代码:D
bool solution(std::string const &str,std::string const &ending) {
long long end = ending.size(),size = str.size();
long long dif = size - end;
string endi = str.substr(dif,end);
if(endi != ending) {
return false;
}
else {
return true;
}
}
这也是我必须要做的任务:
完成解决方案,以便如果传入的第一个参数(字符串)以第二个参数(也是字符串)结尾,则返回true。
请帮助我找出这里的问题,谢谢!
解决方法
通常,字符串str
的大小可以小于字符串ending
的大小。
因此,变量dif
的值可以为负
long long dif = size - end;
在成员函数substr
的调用中使用
string endi = str.substr(dif,end);
由于该函数的第一个参数的类型为std::string::size_type
,这是无符号整数类型,因此使用通常的算术转换将其转换为大的无符号整数值。
可以按照以下演示程序中所示的方式编写该函数。
#include <iostream>
#include <iomanip>
#include <string>
#include <iterator>
#include <algorithm>
bool solution( const std::string &str,const std::string &ending )
{
return !( str.size() < ending.size() ) &&
std::equal( std::rbegin( ending ),std::rend( ending ),std::rbegin( str ) );
}
int main()
{
std::string s( "Hello World!" );
std::cout << std::boolalpha << solution( s,"World!" ) << '\n';
std::cout << std::boolalpha << solution( s,"World" ) << '\n';
return 0;
}
程序输出为
true
false
,
我认为您需要切换end = ending.size()
和size = str.size();
。