3. Create a program which allows the user to swap individual words in an input string. Given a string of input, your program should count and store the number of words in a 2D array. The user can then select the index of the words they want to swap. Your program should swap those two words and then print the entire string to ouput. • Use string prompt "> ". • Use indices prompt "Enter two indices: ". • Remove the trailing newline character from the string. • Save your code as swap_words.c.
Example Run > You can tell a lot about a place by how they treat their people Enter two indices: 7 13 You can tell a lot about a people by how they treat their place
How to write in C?
code:
#include<stdio.h>
#include<string.h>
int main()
{
/*string is to strore input*/
/*words is a 2d array to store words*/
char string[10000];
char words[100][100],t[100];
int strpos,wordpos,count,i,first,second,temp;
printf(">");
scanf("%[^\n]s",&string);
printf("Enter tow indices:");
scanf("%d%d",&first,&second);
strpos=0;
wordpos=0;
count=0;
/*strpos is iterator for string */
/*count is the number of words*/
/*wordpos is the iterator for word*/
while(string[strpos]!='\0')
{
if(string[strpos]==' ')
{
wordpos=0;
strpos++;
count++;
}
else
{
words[count][wordpos]=string[strpos];
strpos++;
wordpos++;
}
}
temp=0;
strcpy(t,words[first]);
strcpy(words[first],words[second]);
strcpy(words[second],t);
i=0;
/*printing the swaped line */
while(i<=count)
{
printf("%s ",words[i]);
i++;
}
}
IF YOU HAVE ANY DOUBT OR IF YOU ENCOUNTER LOGICAL ERROR PLEASE LEAVE A COMMENT.
Get Answers For Free
Most questions answered within 1 hours.