In: Computer Science
Write a C++ function to sort the characters in words in a inputed phrase. DO not sort the characters in the string.
Some of the steps has been done for you. Fill out the program in C++. See below for the expected console output.
Make the program as simple as possible. Use introductory Object-Oriented C++ programming. If all the requirements are met, then this will be upvoted.
Do use the C++ Standard Library headers, do not use the C Standard Library headers (For instance, include cmath instead of math.h)
Do not use cstring’s or any of the cstring functions (strlen(), strcpy(), strcmp(), etc.)
Program:
#include
using namespace std;
string sortPhrase(string phrase){
}
int main(){
string sentence;
cout << "Enter a phrase: ";
getline(cin, phrase);
}
Expected Console Outputs:
Enter a phrase: Hello welcome to the exciting world of programming languages!
The sorted phrase: Hello exciting languages! of programming the to welcome world
Enter a phrase: May the Force be with you!
The sorted phrase: Force May be the with you!
Enter a phrase: There's no place like home.
The sorted phrase: There's home. like no place
The following is the code for above question. Since you were asked for the solution to be as simple as possible, i tried to keep it as simple as such, without using C Standard Library headers and also used basic c++ programming. This can also be done using other complex libraries also(vector,stringstream,strtok etc..).
#include<iostream>
using namespace std;
string sortPhrase(string phrase){ //function to sort the string and return it
int i,j,k=0;
string s[100],t,temp,sentence="";
for(char x:phrase) //split the string based on empty space and store the words in string array
{
if(x==' ') //if space is found
{
s[k++]=t; //put the word before space into string array
t=""; //Now make the string to ""
}
else
{
t=t+x; //else keep on adding each character till space is found
}
}
s[k++]=t; //to put the last word
for(i=0;i<k-1;i++)
{
for(j=i+1;j<k;j++)
{
if(s[i]>s[j]) //sorting the words
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
//Now convert the array of words to form a complete sentence by concatenating them
for(i=0;i<k;i++)
{
if(i!=k-1) //if not last word
{
sentence=sentence+s[i]+" ";
}
else //if last word
{
sentence=sentence+s[i];
}
}
return sentence; //return the sentence
}
int main()
{
string phrase,sentence;
cout<<"Enter a phrase: ";
getline(cin,phrase); //input the phrase
cout<<endl;
sentence=sortPhrase(phrase); //sort the phrase
cout<<sentence; //output the sorted phrase
return 0;
}
I am also attaching the output and code screenshot for your reference.
Output and code screenshot:
#Please dont forget to upvote if you find the solution helpful. Feel free to ask doubts if any, in the comments section. Thank you