#include <stdio.h>
#include <string.h>
/* Create a program that sorts the words of a string based on the first letter of each word.
• You may use stdio.h and string.h.
• Remove any trailing newline \n from your input string.
• Use the insert function that we went over in class.
• Your input prompt should be "Enter a string: ".
• The output should be the sorted string on a new line.
• Save your code as prob2.c.
*/
int isAlpha(char c) {
if (c >= 'a' && c <= 'z') return 1;
if (c >= 'A' && c <= 'Z') return 1;
return 0;
}
void buble_sort(char *words[], int words_count) {
int i,j;
for (int i = 0; i < words_count - 1; i++) {
for (int j = (words_count - 1); j > i; j--) {
if (*words[j - 1] > *words[j]) {
char *temp = words[j - 1];
words[j - 1] = words[j];
words[j] = temp;
}
}
}
}
int main(int argc, char *argv[]) {
char buffer[256];
char result[256];
int len, j;
char *words[128];
int words_count = 0;
// Your input prompt should be "Enter a string: "
printf("Enter a string: ");
fgets(buffer, 256, stdin);
// Remove any trailing newline \n from your input string
len = strlen(buffer);
if (buffer[len-1] == '\n') {
len--;
buffer[len] = '\0';
}
// Sorts the words of a string based on the first letter of each word
for(j=0; j<128; j++) words[j] = NULL;
// First word
if (isAlpha(buffer[0])) words[0] = buffer;
// The rest of the words
if (len > 1) {
j = 1;
words_count = 1;
while (j < len) {
if (isAlpha(buffer[j]) && buffer[j-1]==' ') {
words[words_count] = buffer+j;
words_count++;
buffer[j-1]='\0';
}
j++;
}
printf("\n");
}
// Sorting
buble_sort(words, words_count);
// The output should be the sorted string on a new line.
j = 0;
result[0] = '\0';
while (words[j] != NULL) {
strncat(result, words[j], 256);
strncat(result, " ", 256);
j++;
}
printf("%s\n", result);
}
Comments
Leave a comment