Reputation: 10962
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 c++ ? One liner is preferred. Performance is NOT a concern. std
is preferred, but boost is also an option.
Upvotes: 0
Views: 1323
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
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
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
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