c ++在比较字符串时忽略前置空格,例如:"str1"compare.("str2")= TRUE

Rhe*_*ett 1 c++ string compare char

嗨,我想知道什么是使字符串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
}
Run Code Online (Sandbox Code Playgroud)

所有我需要它str1等于str2我该怎么办?

我做了多次尝试,但它们似乎都没有正常工作.我认为这是因为字符串中的字符数,即:str1的字符数少于str2.

for (int i = 1; i <= str1.length() + 1; i++){
    str1[str1.length() - i ] = str1[str1.length() - (i + 1)];
}
Run Code Online (Sandbox Code Playgroud)

任何帮助赞赏

Pra*_*ian 5

如果可以使用Boost,则可以在boost/algorithm/string.hpp中使用trim功能

str1 = "Front Space";
str2 = " Front Space";
boost::trim_left( str2 ); // removes leading whitespace

if( str1 == str2 ) {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

类似地,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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Hello, World
Hello,   World
Run Code Online (Sandbox Code Playgroud)