C++ Program to find and replace in a string


Suppose, we are given a string s. There is a range, from start to end where start and end are both integers. Whenever we encounter the character stored in variable f within the given range, we replace it with the character stored in r. We find out the string after this replacement operation.

Problem Category

To solve this problem, we need to manipulate strings. Strings in a programming language are a stream of characters that are stored in a particular array-like data type. Several languages specify strings as a specific data type (eg. Java, C++, Python); and several other languages specify strings as a character array (eg. C). Strings are instrumental in programming as they often are the preferred data type in various applications and are used as the datatype for input and output. There are various string operations, such as string searching, substring generation, string stripping operations, string translation operations, string replacement operations, string reverse operations, and much more. Check out the links below to understand how strings can be used in C/C++.

https://www.tutorialspoint.com/cplusplus/cpp_strings.htm

https://www.tutorialspoint.com/cprogramming/c_strings.htm

So, if the input of our problem is like s = "brick", f = 'i', r = 'o', start = 1, end = 5, then the output will be "brock".

Steps

To solve this, we will follow these steps −

for initialize i := start - 1, when i < end, update (increase i by 1), do:
   if s[i] is same as f, then:
      s[i] := r
return s

Example

Let us see the following implementation to get better understanding −

#include<bits/stdc++.h>
using namespace std;
void solve(string s, char f, char r, int start, int end) {
   for(int i = start - 1; i < end; i++)
      if(s[i] == f)
         s[i] = r;
   cout<< s;
}
int main() {
   string s = "brick";
   char f = 'i', r = 'o';
   int start = 1, end = 5;
   solve(s, f, r, start, end);
   return 0;
}

Input

"brick", 'i', 'o', 1, 5

Output

brock

Updated on: 07-Apr-2022

784 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements