Tech & Space



In this tutorial, we will learn how to add a space after comma in a string in C++.

Before writing any code, we should always make an algorithm to determine how to achieve the objective of the program. The algorithm for this program is as follows:

  1. Take an input string containing the comma.
  2. Take an empty string.
  3. Use for loop to access each of its characters. If the character is not a comma, simply 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 the comma character. Then, add a space after the comma to achieve the given objective. For this, we will use the concatenation operator. The sample code illustrates it:

Program to add a space after comma in a string in C++

Now check out the code below:

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

Input string:Hi,Bye
Updated string:Hi, Bye

Program explanation:

Consider an input string ‘s’ containing the comma in it. Now, take another empty string ‘s1’. Then, iterate throughout the input string ‘s’ checking for each of its characters. If the character is not a comma, just concatenate it with the string ‘s1’. If the character is a comma, then concatenate it with an additional space which is the objective of the program. Then store the value of the string ‘s1’ in ‘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!

We have 112 guests and no members online