2

Hi I was wondering what is the shortest way to make string str1 seem equal to string 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
}

All I need it for str1 to equal str2 How can I do it?

I have made multiple attempts but they all don't seem to work correctly. I think it's because of the number of characters in the string, ie: str1 has less characters than str2.

for (int i = 1; i <= str1.length() + 1; i++){
    str1[str1.length() - i ] = str1[str1.length() - (i + 1)];
}

Any help appreciated

Rhett
  • 103
  • 2
  • 8

3 Answers3

6

If you can use Boost, trim functions are available in boost/algorithm/string.hpp

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

if( str1 == str2 ) {
  // ...
}

Similarly, there's trim that removes both leading and trailing whitespace. And all these functions have *_copy counterparts that return a trimmed string instead of modifying the original.


If you cannot use Boost, it's not hard to create your own trim_left function.

#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;
}

Output:

Hello, World
Hello,   World
Praetorian
  • 106,671
  • 19
  • 240
  • 328
1

As others have said, you can use boost. If you don't want to use boost, or you can't (maybe because it's homework), it is easy to make an ltrim function.

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;
}
Geoff Montee
  • 2,587
  • 13
  • 14
1

LLVM also has some trim member functions for their StringRef class. This works without modifying your string and without making copies, in case that's important to you.

llvm::StringRef ref1(str1), ref2(str2);
ref1.ltrim();
ref2.ltrim();
if (ref1 == ref2) {
    // match
}
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274