C ++在比较字符串时忽略前空格,例如:"str1"比较。( " str2" ) = 真

c++ ignore front spaces when comparing strings eg: "str1"compare.(" str2") = TRUE

本文关键字:比较 str1 str2 例如 字符串 空格      更新时间:2023-10-16

嗨,我想知道让字符串 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( " ntHello,   World" );
  trim_left( s1 ); trim_left( s2 );
  std::cout << s1 << std::endl;
  std::cout << s2 << std::endl;
}

输出:

Hello, World
Hello,   World

正如其他人所说,您可以使用boost .如果你不想使用boost,或者你不能(也许是因为这是家庭作业),很容易制作一个 ltrim 函数。

string ltrim(string str)
{
    string new_str;
    size_t index = 0;
    while (index < str.size())
    {
        if (isspace(str[index]))
            index++;
        else
            break;
    }
    if (index < str.size())
        new_str = str.substr(index);
    return new_str;
}

LLVM也为他们的StringRef类提供了一些修剪成员函数。 这无需修改字符串和复制即可工作,以防这对您很重要。

llvm::StringRef ref1(str1), ref2(str2);
ref1.ltrim();
ref2.ltrim();
if (ref1 == ref2) {
    // match
}