In: Computer Science
SOLUTION-
I have solve the problem in C++ code with comments and screenshot
for easy understanding :)
CODE-
//c++ code
#include <iostream>
using namespace std;
// declarations for function asked in assignment.
int NumWords(string &line);
int NumNonWSCharacters(string &line);
char PrintMenu();
void CharReplace(string &line, char rep,char repw);
//main function
//its takes input string from user and call PrintMenu()
// based of choice while loop will run until user enters 'q' or
Ctrl-d
//choice is 'w' it call the NumWords(&string) and returns count
of letters in it.
//choice is 'c' it call the NumNonWSCharacters(&string) and
returns the letter without space
//choice is 'r' it call CharReplace(&string,char,char)
//main function
int main()
{
string line;
char choice,rep,repw;
cout<<"Enter a line of text: ";
getline(cin, line); //gets input
cout<<"You Entered: "<<line<<endl;
choice=PrintMenu(); //user choice
while(choice!='q'|| getline(std::cin, line)){
if(choice=='w')
{
cout<<"Number of words:
"<<NumWords(line)<<endl;
}
else if(choice=='c')
{
cout<<"Number of non-whitespace characters:
"<<NumNonWSCharacters(line)<<endl;
}
else if(choice=='r')
{
cout<<"Enter a character to find: ";
cin>>rep;
cout<<"Enter a character to replace: ";
cin>>repw;
CharReplace(line,rep,repw);
cout<<"New String: "<<line<<endl;
}
choice=PrintMenu();
}
return 0;
}
//PrintMenu to show options and return choice based on input.
char PrintMenu(){
char choice;
cout<<"\nOptions"<<endl;
cout<<"w - Number of words"<<endl;
cout<<"c - Number of non-whitespace
characters"<<endl;
cout<<"r - Replace a character"<<endl;
cout<<"q - Quit"<<endl;
cout<<"Choose an option: ";
cin>>choice;
return choice;
}
//NumWords(&string) it loop the whole string untill '\0' and
return count.
int NumWords(string& line){
int count=0;
for(int i=0;line[i]!='\0';i++){
count++;
}
return count;
}
//NumWords(&string) it loop the whole string untill '\0' and if
char is space it skips and return count.
int NumNonWSCharacters(string& line){
int count=0;
for(int i=0;line[i]!='\0';i++){
if(!isspace(line[i]))
count++;
}
return count;
}
// it replace the rep with repw while iterating each char
void CharReplace(string& line, char rep,char repw){
for(int i=0;line[i]!='\0';i++){
if(line[i]==rep){
line[i]=repw;
}
}
}
SCREENSHOT-
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL
SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------