Replace character of a string

Replace character of a string-Given a string S, print it after changing the middle element to *(if the length of the string is even, change the 2 char

Replace a Particular Character in a given string

In this post, we will be discussing the Program to Replace a character with a special character in a given string i.e., within a given string we have to change the character of the middle index by the special character given to replace. Also, the required logic is discussed and the source code is written in C++ which is compiled successfully to provide the best results.

Problem Description

Given a string S, print it after changing the middle element to * (if the length of the string is even, change the 2 middle elements to *).

Sample Testcase:
INPUT
hello
OUTPUT
he*lo

Explanation:

In this, we will be discussing the Program to Replace a character with a special character in a given string i.e., within a given string we have to change the character of the middle index by the special character given to replace. This can be performed by finding the middle position of the string and replace that position character with the *. If the length of the inputted string is odd then only replace the middle position character. If the length of the inputted string is even then replace the middle two-position character.

Logic to follow to come up with the solution:

1. Declare and input the required set of variables and strings.

2. Find the length of the inputted string using strlen() function.

3. Check if the calculated string length is even or odd.

4. Now using the conditional statement if-else() replace the middle position character of the string.

5. If the length of the inputted string is odd then only replace the middle position character with *.

6. Else, the length of the inputted string even then replaces the middle two-position character with *.

7. At last, finally print the replaced string as the output.

Let's write the code for the required problem:

Code:

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22``` ```#include #include using namespace std; int main() { char str[100]; cin>>str; int l=strlen(str); int m=l/2; if(l%2!=0) { str[m]='*'; } else { str[m]='*'; str[m-1]='*'; } cout<

Sample test cases have been passed Successfully

If you liked this post, then share this with your friends and if anything is confusing or incorrect then let me know in the comment section.

Thanks from my side, this is Mayank, keep learning and exploring !!

Mayank Pathak is the editor and blogger at "The Coding Bro".He loves to codes, learn new technologies, and write the coding solutions and articles for the communities of learners, especiall…