Write a C program called pointer sorter, which accept a input string. The input
ID: 3785940 • Letter: W
Question
Write a C program called pointer sorter, which accept a input string. The input string contains sorted words, and your job is to break them out into single strings and sort them, finally output them per line in desceding alphabetical order.
For example, if the input String is "sdf gdf asd", the output would be
asd
gdf
sdf
Any non-alphabetic order could be regarded as a separator, e.g.: “sdf1gdf,asd” is equal to the input string above, and they should have the same output.
Using the knowledge of pointers and dynamic memory to write this program, and the length of the input string is not known, so you will not know how much memory to allocate and how many pointers to deal with the input string in the begining.
The way to solve this program is to determine the length of the input string first. You should go through the input string and test each character until it finds a separator. After the separator was found, you can use malloc() to request memory and memcpy() to copy strings into a new list of strings.
In addition, the number of total component strings is not known, so you should use a extendable data structure to store the input strings.
When it comes to sorting, you should realize that you dont know the length of the strings, so you should compare each component string, and insert them into the new input string one by one in a sorted order.
Write a program that is efficient and fast.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort_string(char*);
int main()
{
char string[100];
printf("Enter some text ");
gets(string);
sort_string(string);
printf("%s ", string);
return 0;
}
void sort_string(char *s)
{
int c, d = 0, length;
char *pointer, *result, ch;
length = strlen(s);
result = (char*)malloc(length+1);
pointer = s;
for ( ch = 'a' ; ch <= 'z' ; ch++ )
{
for ( c = 0 ; c < length ; c++ )
{
if ( *pointer == ch )
{
*(result+d) = *pointer;
d++;
}
pointer++;
}
pointer = s;
}
*(result+d) = '';
strcpy(s, result);
free(result);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.