Part E. String Sorting 1. Write a function called sortWords that takes as input
ID: 3915254 • Letter: P
Question
Part E. String Sorting 1. Write a function called sortWords that takes as input parameter a null i.e. '10') terminated string line, where line would contain an English sentence. 2. Assume that the delimiters are space, comma, semicolon and period 3. The function extracts each word from the sentence (without any punctuation or spacing) and then prints them after sorting 4. The function returns a void type. For example: char str[l - "hello world, how are you today." sortWords (str); would print the following: List of Sorted Words are hello how today world youExplanation / Answer
Although the question does not mention the language for the code I am assuming it is C language as we are using character array rather than a 'String' data type. Thus the code is in C language.
For sorting, I have used simple bubble sort because it is simplest to implement and understand. Detailed comments have been added for better understanding.
Code:
#define MAX 50
#include<stdio.h>
#include<string.h>
void swap(char words[MAX][MAX],int i, int j)
{
int k=0,l1,l2;
char t;
//Calculate Length
l1=strlen(words[i]);
l2=strlen(words[j]);
while(words[i][k]!='' && words[j][k]!='')//Swapping character by character
{
t=words[i][k];
words[i][k]=words[j][k];
words[j][k]=t;
k++;
}
while(words[i][k]!='')//Swapping remaining characters of words[i]
{
words[j][k]=words[i][k];
k++;
}
while(words[j][k]!='')//Swapping remaining characters of words[j]
{
words[i][k]=words[j][k];
k++;
}
words[i][l2]='';//Place at the end of both words
words[j][l1]='';
}
void sortWords(char line[])
{
//Variable Declaration
int i,j,cnt,ind;
char ch;
char words[MAX][MAX];
line=strlwr(line);//Converting line to all lower case
i=0;cnt=0;ind=0;
//Word Extraction
while(line[i]!='')
{
ch=line[i];//Extracting each char
if(ch==' ' || ch==',' || ch==';' ||ch=='.')//Checks if char is a delimiter
{
if(ind!=0)//If the extracted word length is > 0 then store it.
{
words[cnt][ind]='';
ind=0;
cnt++;
}
}
else//Stores each character in words[][]
{
words[cnt][ind]=ch;
ind++;
}
i++;
}
//Sorting using simple bubble sort technique
for(i=0;i<cnt;i++)
{
for(j=0;j<cnt-i-1;j++)
{
if(strcmp(words[j],words[j+1])>0)
{
swap(words,j,j+1);//Swap word j,j+1. 'words' array is passed by reference
}
}
}
printf(" List Of Sorted Words:");//Print
for(i=0;i<cnt;i++)
{
printf(" %s",words[i]);
}
}
int main()
{
char str[] = "Hello world, how are you today.";//Alternatively, accept input from the user
sortWords(str);
}
Output:
List Of Sorted Words:
are
hello
how
today
world
you
Feel free to comment if you want clarifications or edit to the answer.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.