2012-10-16 25 views
1

您好我想知道什麼是使串STR1似乎等於字符串STR2的最短途徑C++比較字符串例如,當忽略前面的空格:「STR1」比較(」 STR2" )= TRUE

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)]; 
} 

任何幫助表示讚賞

回答

5

如果可以使用Boost,裝飾功能升壓/算法/ 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 
1

正如其他人所說,你可以使用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; 
} 
1

LLVM對於StringRef類也有一些修剪成員函數。這可以在沒有修改你的字符串的情況下工作,也不需要複製,以防對你很重要。

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