Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace substring with another substring C++

How could I replace a substring in a string with another substring in C++, what functions could I use?

eg: string test = "abc def abc def"; test.replace("abc", "hij").replace("def", "klm"); //replace occurrence of abc and def with other substring 
like image 668
Steveng Avatar asked Jan 10 '11 03:01

Steveng


People also ask

How do I replace a substring with another substring?

Algorithm to Replace a substring in a stringInput the full string (s1). Input the substring from the full string (s2). Input the string to be replaced with the substring (s3). Find the substring from the full string and replace the new substring with the old substring (Find s2 from s1 and replace s1 by s3).

What function is to replace a substring from a string in C?

Replace(Char, Char)

How do you replace all occurrences of substring in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

Can you rewrite a string in C?

You need to copy the string into another, not read-only memory buffer and modify it there. Use strncpy() for copying the string, strlen() for detecting string length, malloc() and free() for dynamically allocating a buffer for the new string.


1 Answers

In c++11, you can use std::regex_replace:

#include <string> #include <regex>  std::string test = "abc def abc def"; test = std::regex_replace(test, std::regex("def"), "klm"); // replace 'def' -> 'klm' // test = "abc klm abc klm" 
like image 136
Jingguo Yao Avatar answered Sep 22 '22 22:09

Jingguo Yao