您好,我想知道让字符串 str1 看起来等于字符串 str2 的最短方法是什么
str1 = "Front Space";
str2 = " Front Space";
/*Here is where I'm missing some code to make the strings equal*/
if (str1.compare(str2) == 0) { // They match
cout << "success!!!!" << endl; // This is the output I want
}
我只需要它让 str1 等于 str2
我该怎么做?
我已经进行了多次尝试,但它们似乎都无法正常工作。我认为这是因为字符串中的字符数,即:str1 的字符数少于 str2。
for (int i = 1; i <= str1.length() + 1; i++){
str1[str1.length() - i ] = str1[str1.length() - (i + 1)];
}
感谢任何帮助
如果你可以使用 Boost,修剪函数在 boost/algorithm/string.hpp 中可用
str1 = "Front Space";
str2 = " Front Space";
boost::trim_left( str2 ); // removes leading whitespace
if( str1 == str2 ) {
// ...
}
同样,trim
可以删除前导空格和尾随空格。所有这些函数都有 *_copy
对应项,它们返回修剪后的字符串而不是修改原始字符串。
如果您不能使用 Boost,创建您自己的 trim_left
函数并不难。
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
void trim_left( std::string& s )
{
auto it = s.begin(), ite = s.end();
while( ( it != ite ) && std::isspace( *it ) ) {
++it;
}
s.erase( s.begin(), it );
}
int main()
{
std::string s1( "Hello, World" ), s2( " \n\tHello, World" );
trim_left( s1 ); trim_left( s2 );
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
}
输出:
Hello, World
Hello, World