How to remove a particular substring from a string?

76,285

Solution 1

How about:

// Check if the last three characters match the ext.
const std::string ext(".gz");
if ( s != ext &&
     s.size() > ext.size() &&
     s.substr(s.size() - ext.size()) == ".gz" )
{
   // if so then strip them off
   s = s.substr(0, s.size() - ext.size());
}

Solution 2

You can use erase for removing symbols:

str.erase(start_position_to_erase, number_of_symbols);

And you can use find to find the starting position:

start_position_to_erase = str.find("smth-to-delete");

Solution 3

If you're able to use C++11, you can use #include <regex> or if you're stuck with C++03 you can use Boost.Regex (or PCRE) to form a proper regular expression to break out the parts of a filename you want. Another approach is to use Boost.Filesystem for parsing paths properly.

Share:
76,285
John
Author by

John

Live Every Moment

Updated on February 24, 2020

Comments

  • John
    John about 4 years

    In my C++ program, I have the string

    string s = "/usr/file.gz";
    

    Here, how to make the script to check for .gz extention (whatever the file name is) and split it like "/usr/file"?

  • Vlad
    Vlad about 12 years
    regex should be an overkill for such a simple task
  • Aligus
    Aligus about 12 years
    substr() always creates new object. It's not sounds well by performance reasons.
  • Component 10
    Component 10 about 12 years
    @Alexander: True, but there was no mention of performance considerations in the question.
  • MSalters
    MSalters about 12 years
    With very similar code, I managed to wipe 3 complete PCs(*). You probably want s.size() > 3, as ".gz" is a hidden file and should not be stripped to "". ( * I stripped too much, added * and then did a rm -rf /* )
  • Component 10
    Component 10 about 12 years
    @MSalters: An impressive achievement! Tell me you didn't run it as root? :) I only really intended this as a simple example for the OP but I think your point is very important in context and I've changed accordingly. Thanks for sharing it!
  • Roland Illig
    Roland Illig over 4 years
    This code looks more complicated than necessary. Doesn't C++ have an ends_with method like in Java or Python? And what is the point of s != ext? The code would work equally well without that comparison.