How to add space after dot(.) or comma(,) in C++ strings

Hey learners, let us learn a new concept based on strings and that is how to add a space after a dot(.) or comma(,) in a string in C++. This can also clear the concept of how to add a character after a specified character in a string. Before diving into the concept, let us know the basic difference between a character and a string.

CHARACTER VS STRING:
Character is a data type that stores a single character which can be a letter, a number, whitespace, etc enclosed in single quotes whereas a string is a sequence of characters ending with a null character that can be a sentence or a group of characters.

Implementation for adding a space after a specified character (say dot and comma)

#include<iostream>
#include <cstring>
using namespace std;
int main(){ 
    int i,j;
    string str1 = "Hello,I am a learner at codespeedy.I know C++.";
    cout<< "The input string is: ";
    cout << str1<<endl;
    string str2 = "";
    for(i=0,j=0;str1[i]!='\0';i++,j++) { 
        if(str1[i]=='.' || str1[i]==',') {
            str2 = str2 + str1[i] + " ";
        } else { 
            str2 = str2 + str1[i];
        }
    }
    str1 = str2;
    cout << "The output string is: ";
    cout <<str1;
}

OUTPUT:

The input string is: Hello,I am a learner at codespeedy.I know C++.
The output string is: Hello, I am a learner at codespeedy. I know C++.

EXPLANATION OF CODE:

  • Firstly, include the required headerfiles. Since we are dealing with the cout and cin, we need to include the iostream headerfile as well as we are dealing with the strings we need to include the string package of C language so when we are including a C language package into C++ code, we need to include the headerfile name prefixed with letter ‘c’.
  • After including the required headerfiles, we need to take the input string this can be done by declaring string type variable and assigning the input string to it and we also declare a string with null value in it. Now we move character by character in the input string. If the specified character[dot or a comma] is encountered, we simply add a space character to the null string in addition to the specified character(dot or comma). otherwise, we simply assign the character of input string to the output string. This process is to be done till we encounter a null character in the input string which specifies the end of the string.
  • Lastly, we assign the whole string to the input string and display it on the output screen.

Leave a Reply

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