Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a prefix or a suffix from a string in c++? [duplicate]

Some others have asked about

  • how to remove an arbitrary substring from a string in c++.
  • how to check whether a string ends with a given prefix
  • how to check whether a string ends with a given suffix

However, it has not yet been asked how to remove a prefix or a suffix from a string in c++. Assuming that we know that a given string starts with a specific prefix/suffix, some specialized methods may be used.

So: Given the following, how do we remove the prefix and suffix?

  std::string prefix = "prefix.";
  std::string suffix = ".suffix";
  std::string full_string = "prefix.content.suffix";
  std::string just_the_middle = ???;
like image 773
Jasha Avatar asked Dec 13 '25 02:12

Jasha


1 Answers

Since we know ahead of time that full_string starts/ends with prefix/suffix, one can use std::string::substr:

  std::string prefix = "prefix.";
  std::string suffix = ".suffix";
  std::string full_string = "prefix.content.suffix";
  
  // prefix removal
  std::string result1 = full_string.substr(prefix.length());
  
  // suffix removal
  std::string result2 = full_string.substr(0, full_string.length() - suffix.length());
like image 71
Jasha Avatar answered Dec 14 '25 16:12

Jasha