I need to sort each word in a sentence alphabetically while keeping the words separate from one another. I am not allowed to use the strtok() function.
Sample input: I would really appreciate some help
Sample output: I dlouw aellry aaceeipprt emos ehlp
I have managed to sort the entire string alphabetically.Which gives me an output of: Iaaacdeeeeehillllmooppprrstuwy
I am not sure If I should nest my current code into a loop which would start over every time there is a space. Or if I need to read my string into a two-dimensional array and sort each word separately.
I am also not sure if it would make more sense to compare the values of each char or to count the occurrence of each letter within the string. I have a version of each which gives me the output shown above.
Thanks in advance.
Version comparing chars:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char str[100];
printf("Please type a sentence :\n");
scanf("%[^\n]s", str);
printf("\nAlphabetical order:\n:);
char temp;
int i, j;
int n = strlen(str);
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (str[i] > str[j]) {
temp = str[i];
str[i] = str[j];
str[j] = temp1;
}
}
}
printf(str);
return 0;
}
Version counting occurrences of each char:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char ch, input[100], output[100];
int no[26] = {0}, n, c, t, x;
printf("Please type a sentence:\n");
scanf("%s", input);
n = strlen(input);
for (c = 0; c < n; c++)
{
ch = input[c] - 'a';
no[ch]++;
}
t = 0;
for (ch = 'a'; ch <= 'z'; ch++)
{
x = ch - 'a';
for (c = 0; c < no[x]; c++)
{
output[t] = ch;
t++
}
}
output[t] = '\0';
printf("%s\n", output);
return 0;
}