
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find and Replace in a String using C++
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