Ads by ProfitSence
Close

C++ Remove subString from String

Last Updated on Wednesday 5th Oct 2022

Remove substring from String C++

Erase

You can use erase for removing symbols.

  • Erase characters from string.
  • Erases part of the string, reducing its length.
			
					#include <iostream>

#include <string>

int main() {
  std::string str("This is an example sentence.");
  std::cout << str << '\n'; // "This is an example sentence."
  str.erase(10, 8);
  std::cout << str << '\n'; // "This is an sentence."
  str.erase(str.begin() + 9);
  std::cout << str << '\n'; // "This is a sentence."
  str.erase(str.begin() + 5, str.end() - 9);
  std::cout << str << '\n'; // "This sentence."
  return 0;
}

			
	
			
					This is an example sentence.
This is an sentence.
This is a sentence.
This sentence.

			
	

You can use find to find the starting position. Searches the string for the first occurrence of the sequence specified by its arguments.

C++ remove substring from string

			
					#include <iostream>

#include <string>

int main() {
  std::string str("There are two needles in this haystack with needles.");
  std::string str2("needle");

  // different member versions of find in the same order as above:
  std::size_t found = str.find(str2);
  if (found != std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';

  found = str.find("needles are small", found + 1, 6);
  if (found != std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';

  found = str.find("haystack");
  if (found != std::string::npos)
    std::cout << "'haystack' also found at: " << found << '\n';

  found = str.find('.');
  if (found != std::string::npos)
    std::cout << "Period found at: " << found << '\n';

  // let's replace the first needle:
  str.replace(str.find(str2), str2.length(), "preposition");
  std::cout << str << '\n';

  return 0;
}

			
	
			
					first 'needle' found at: 14
second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles.

			
	

References