Thursday, July 30, 2009

Comparing words to see if one is alphabetically before another, in C?

Where each letter of each word is stored in a listADT?





(the header would be something like...)





boolean listBefore(listADT list1, listADT list2)





- returning TRUE if the word in list1 is alphabetically before that in list2, and returning FALSE if it is not (I have written and included a boolean library obviously).





where listADT is a linked list, with each node made up of a 'char' component for the letter, and a pointer to the next letter.





If that makes sense. I'm quite new to C.





Can anyone tell me how to do this?

Comparing words to see if one is alphabetically before another, in C?
No, honestly using a linked list makes no sense and vastly complicates things.





Make your ADT a character array (i.e. C-string). If you are allowed to do so, use strcmp or strncmp. If those are forbidden and the point of the exercise is to write the comparison code yourself then you have more work to do.





Loop through the strings comparing each char. Watch for the null terminators on the strings. If the chars aren't equal, subtract the string2 char from the string1 char and return it. Whether it is positive or negative tells you which string is greater.
Reply:.... Why are you using a Linked list???





that aside just begin at the head of the list and do (char1%26lt;char2 %26amp;%26amp; char1!=char2). If that passes word one is first in the alphabet. If it failed do a comparsion on the same 2 chars but use %26gt; instead. If that passes then word 2 is first in the alphabet.


No comments:

Post a Comment