Remove prefix from a string in C++
This post will discuss how to remove the prefix from a string in C++.
The standard solution to remove part of a string is using the std::string::erase member function. It can be used as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> int main() { std::string str = "ThinkPad"; std::string prefix = "Think"; str.erase(0, prefix.length()); std::cout << str << std::endl; // Pad return 0; } |
To get the copy of the string with the prefix removed, we can use the std::string::substr function:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> int main() { std::string str = "ThinkPad"; std::string prefix = "Think"; std::string result = str.substr(prefix.length()); std::cout << result << std::endl; // Pad return 0; } |
It is advisable to check whether a string starts with a prefix before removing it. This can be achieved using C++20 std::string.starts_with() or std::string::substr function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> int main() { std::string str = "ThinkPad"; std::string prefix = "Think"; std::string result = str.starts_with(prefix)? str.substr(prefix.size()): str; std::cout << result << std::endl; // Pad return 0; } |
That’s all about removing the prefix from a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)