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

C++ c++;在比较字符串时忽略前面的空格,例如:";str1“;比较(";str2";)=TRUE,c++,string,char,compare,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 i

嗨,我想知道什么是使字符串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.compare(str2)==0){//它们匹配

cout如果可以使用Boost,则Boost/algorithm/string.hpp中提供了微调功能

类似地,还有删除前导和尾随空格的
trim
。所有这些函数都有
*\u copy
对应项,它们返回一个修剪过的字符串,而不是修改原始字符串


如果您不能使用Boost,那么创建自己的
trim\u 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;
}
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;
}

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

#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;
}
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;
}
string-ltrim(string-str)
{
串新_str;
尺寸指数=0;
而(索引
LLVM还为其类提供了一些修剪成员函数。这可以在不修改字符串和不制作副本的情况下工作,以防这对您很重要

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