darune
darune

Reputation: 10962

Simplest way to remove first part of a string if it matches (from beginning) ? (using boost is ok)

std::string str_a = "Hello World";
std::string str_b = "Hello ";

If string matches from beginning, remove it or return it in a new string with result, doesn't matter. Result should then be "World".

Whats the most stupid and simplest way to this with ? One liner is preferred. Performance is NOT a concern. std is preferred, but is also an option.

Upvotes: 0

Views: 1323

Answers (4)

Like
Like

Reputation: 1538

if (str_a.compare(0, str_b.size(), str_b) == 0)
    str_a.erase(0, str_b.size());

Use erase to avoid constructing a temporary string

Upvotes: 0

john
john

Reputation: 87944

if (str_a.compare(0, str_b.size(), str_b) == 0)
    str_a = str_a.substr(str_b.size());

Seems straightforward and efficient.

Upvotes: 3

IzZy
IzZy

Reputation: 384

Probably not the best performance, but in one line:

std::string str_c = (str_a.find(str_b) == 0) ? str_a.substr(str_b.size()) : str_a;

Upvotes: 0

Cornholio
Cornholio

Reputation: 454

#include <iostream>
#include <string>

int main()
{
   std::string a = "Hello World";
   std::string b = "Hello ";

   if (a.find(b) == 0)
   {
       std::cout << "\"" << a.substr(b.length()) << "\"\n";
   }

   return 0;
}

Upvotes: 4

Related Questions