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

标签 c++ string char compare

<分区>

您好,我想知道让字符串 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

关于c++ 在比较字符串时忽略前面的空格,例如 : "str1"compare. ("str2") = TRUE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12906344/

相关文章:

c++ - C++扫描字符串的方法

c++ - Linux 分配器不会释放小块内存

c++ - 从命令行构建 x64 C++ 项目说 : This operation should only take place on the UI thread

c++ - 在文本模式下使用 seekg()

c++ - 如何制作 char 的拷贝而不是 C++ 中的引用

c++ - 由另一个字符串的第一个字符组成的字符串 - 为什么它还打印完整的原始字符串?

ruby-on-rails - Ruby 和编码转换

c# - 消除字符串中 "insignificant"重复字符的最简单方法

python - 如何使用 str.join() 而不是 "+="来加入带分隔符的字符串列表?

iphone - 将 NSString* 转换为 char?