1

Some others have asked about

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 = ???;
Jasha
  • 5,507
  • 2
  • 33
  • 44
  • 1
    when you know how to remove an arbitrary substring, you also know how to remove a pre/suffix, no? – 463035818_is_not_an_ai Apr 24 '21 at 11:14
  • Yes, it is true that techniques for removing arbitrary substrings will work to remove a prefix/suffix. However, given techniques for removing a prefix/suffix, those techniques will not necessarily work to remove an arbitrary substring. My intention here was to collect techniques for removing a prefix/suffix specifically, which might involve cleaner / clearer code than techniques that are applicable to arbitrary substrings. – Jasha Apr 24 '21 at 11:33
  • 1
    sorry, but they dont (involve much cleaner / clearer code). The accepted answer on "How to remove arbitrarys?" is specifically about removing a suffix (and the questions too, just the title is more general) – 463035818_is_not_an_ai Apr 24 '21 at 11:37
  • The post you linked actually does a better job for removing the suffix than your answer on this post. – ChrisMM Apr 24 '21 at 11:43

1 Answers1

1

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());
acraig5075
  • 10,588
  • 3
  • 31
  • 50
Jasha
  • 5,507
  • 2
  • 33
  • 44
  • 4
    It is bad suggestion because you don't remove "prefix." or ".suffix", you remove 7 arbitrary characters. – gudvinr Nov 17 '22 at 11:58