In: Computer Science
Write a function in C++ that reads the line separates it with comma.
Input:
hello how are you.
hello world
hello_world
I am there for you!
Output:
hello, how, are and you.
hello and world
hello_world
I, am, there, for and you!
just add a comma and (and) before the last word.
CODE IN C++ ONLY.
Here I am writing the code in C++ and after this // i will comment about that line to understand
our logic will be for this program like this.
first we take string in a function then after this function will count how much space are in there in the sentence then after function will see for space if they not getting space so it will print that word if they will get space then count increment and comapre if count == how much counted space intially then print and it will at before last word else print , .
program code:
#include<iostream>
#include<string.h> // header file for string
using namespace std;
void add(string str) // declaring a function with input of str
{
int j=0,i=0,count=0; // declare these variable for we used in further function
for(int k=0;k<=str.size();k++) // function will run till string length
{
if(str[k]==' ') // it will count for all the space in the string
{
j++;
}
}
for(i=0;i<=str.size();i++)
{
if(str[i]==' ') // checking for spcae in string if come and program enter this loop otherwise it will go to else part
{
count++; //first if space found then count incremented
if(count == j) // now checking for all the space calculated is equal to space found till now if match then print and it mean cursor in at before the last word
{
cout<<" and ";
}
else // else print comma (,)
{
cout<<", ";
}
}
else
{
cout<<str[i]; // if space is not found then print that word
}
}
}
int main() // main function
{
string s1="hello how are you."; // declartion of strings
string s2="hello world";
string s3="hello_world";
string s4="i am there for you!";
add(s1); // now calling function for string 1
cout<<endl; // move the cursor to new line
add(s2);
cout<<endl;
add(s3);
cout<<endl;
add(s4);
return 0;
}
output :