Insert space after a certain character in C++

In this tutorial, we will learn how to insert a space after a certain character in a string in C++.

Before start writing our program, It is good to make an algorithm to determine how to achieve the objective of that program. The algorithm for this program is as given below:

  1. Take an input string containing a certain character.
  2. Take an empty string.
  3. Use the for loop to access each of its characters. If the character is not that certain character, concatenate it to the empty string else concatenate it with additional space.

To implement this, we should iterate in a loop throughout the string length to find that certain character. Then, add a space after a certain character to achieve the given objective. For this, we will use the concatenation operator. The sample code illustrates it:

C++ program to insert a space after a certain character in a string

Check out our C++ code given below:

#include <iostream>
using namespace std; 
string replace(string str, char c)
{
    string s1="";
    for(int i=0;i<str.length();i++) 
    {
        if(str[i]!=c) 
        s1=s1+str[i];
        else 
        s1=s1+str[i]+" ";
    }
    return s1;
}
int main()
{ 
    string s="Hi:Bye:Hello:Start:End"; 
    char c=':';
    cout<<"Input string:"<<s<<endl; 
    s=replace(s,c);
    cout<<"Updated string:"<<s<<endl;
    return 0; 
}

Output:

Input string:Hi:Bye:Hello:Start:End
Updated string:Hi: Bye: Hello: Start: End

Program explanation:

Consider an input string ‘s’ and a certain character (say ‘:’). Define a function replace with two arguments: an input string and a character and with the return type string. Now, take another empty string ‘s1’. Then, iterate throughout the input string using a for loop checking for each of its characters. If the character is not a ‘:’, just concatenate it with the string ‘s1’. If the character is a ‘:’, then concatenate it with an additional space which is the objective of the program. Call the replace function with values input string and ‘:’ and store the returned value in the string ‘s’ and display the result on the screen.

I hope this post was helpful and it helped you clear your doubts!

Thanks for reading. Happy coding!

Recommended Posts:
Adding comments in C++
Adding A Character To A String in C++

Leave a Reply

Your email address will not be published. Required fields are marked *