Computer Science Canada help - listing strings in alphbetical order |
Author: | whoareyou [ Wed Apr 20, 2011 7:31 pm ] | ||
Post subject: | help - listing strings in alphbetical order | ||
So basically, this program that I'm supposed to be making has a part where I need to be sort these 2 entered strings alphabetically. So far, what I've done is to create a for loop that will check the first letter of the two words and will determine the order according to the first letter. But then I realized that there were problems, because what if both words started with the same letter, then I'd have to check the next letter, and if that letter was the same, I'd have to check the next letter. If the two strings were equal, I could check that at the beginning by using a simple if statement. So I think, fundamentally, my question is how would I go about checking every letter of the words, and determining whichever one comes first? Oh, and also, if all the letters were the same but one of the strings were longer, then the first string would be first, then the second.
|
Author: | apython1992 [ Wed Apr 20, 2011 8:12 pm ] | ||
Post subject: | RE:help - listing strings in alphbetical order | ||
What you really want is to treat each character of the strings individually, and compare each character as you progress through the string. In Java, you can convert a string to a character array with
Start with that and come back if you have another question. |
Author: | whoareyou [ Wed Apr 20, 2011 8:55 pm ] |
Post subject: | RE:help - listing strings in alphbetical order |
I haven't learned arrays yet, so I guess I can't do that. However, what I've done so far is created a "while" loop to find out at what index the characters aren't the same. But then they're are problems that will occur if the index is too larger for one string than the other. |
Author: | SmokeMonster [ Wed Apr 20, 2011 11:48 pm ] | ||
Post subject: | Re: help - listing strings in alphbetical order | ||
There is an equalsIgnoreCase function in java to compare two strings and determine which one is greater, if you are allowed to use that. Otherwise apython1992 is correct, if you don't know arrays you don't have to use arrays, you just have to go through both strings character by character. Use a while loop to go through the strings character by character
Then just compare the the two chars, if one of them is less then the other the you have found the "smaller" string alphabetically, print the strings and get out of the loop. If the two characters were equal move on with the loop. If the strings are the same the loop will run till the length of the strings and you'd know that the strings were the same. |
Author: | whoareyou [ Thu Apr 21, 2011 7:59 pm ] | ||
Post subject: | Re: help - listing strings in alphbetical order | ||
I think using the "b = s1.compareToIgnoreCase(s2); " method does it all.
I think this is error proof. |