Hi, I'm working on a little program, both for school and just to get better with C, which is supposed to do the following:
- Accept a string input by a user
- Store the string in a character array
- Print out user's string
- Reverse the order of words in user's string (this is an example string = string example an is this)
- Print out the new string
- Sort the letters in each word in alphabetical order (example = aeelmpx)
- Print out the new string
I've done most of my coding using C++ and C# so on top of dealing with the slightly different syntax of C, I've run into a problem on the final two steps, the alphabetical sorting.
So far, this is the code I have:
To clarify some things beforehand, I'll explain some things that I think might be questioned. First, I use void main() instead of int main() because we're supposed to have the program run indefinitely until it's manually shut down so I do not want to return 0 to shut off the program as I would normally. Second, I know scanf() is better than gets() (or at least, I think it is if my research was right) but we're also required to meet a specific size for the code file and whenever I use scanf(), the size of the file comes dangerously close to our limit. Finally, everything up to this point works fine so unless you see something that is horribly wrong, it's not my primary concern to change any of the code that I already have.Code:// Function to reverse the entire string void reverseString(char *start, char *end) { // Initialize temporary variable char temp; while (start < end) { temp = *start; *start++ = *end; *end-- = temp; } } void main (void) { // Initialize variables char string[30]; char *end, *x, *y; while (1) { printf("Enter a string: "); gets(string, 30); printf("Your string: %s", string); // Find end of the string for(end = string; *end; end++); // Reverse the entire string reverseString(string, end-1); // Create new start and end points x = string-1; y = string; // Until the end of the string is reached while(x++ < end) { // Reverse each word if(*x == '\0' || *x == ' ') { reverseString(y, x-1); y = x+1; } } printf("\nYour reversed string: %s\n\n", string); } }
With that out of the way, I want to ask if anyone can point me in the right direction as to how to go about sorting the letters of each word in alphabetical order. I know I can use the same while loop to split the string into separate words but I'm just at a complete loss as to how to code the function to sort the letters alphabetically. I don't just want the code either but rather, an explanation as to how to do it first and if I can't figure it out, I'll come back. If anyone can help me out, I'd greatly appreciate it.