Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a particular substring from a string?

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"?

like image 275
John Avatar asked May 10 '12 10:05

John


People also ask

How do you remove a specific substring from a string in C++?

Remove specific substring from string in C++ std::string::find() is used to find the starting index of a substring in the original string. std::string::erase() is used to erase the substring from the original string.

How do I remove a specific substring from a string in Python?

translate() is another method that can be used to remove a character from a string in Python. translate() returns a string after removing the values passed in the table. Also, remember that to remove a character from a string using translate() you have to replace it with None and not "" .

How do I remove a specific character from a string?

Python Remove Character from String using replace() We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.


2 Answers

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");
like image 71
Aligus Avatar answered Oct 12 '22 16:10

Aligus


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());
}
like image 26
Component 10 Avatar answered Oct 12 '22 16:10

Component 10