views:

136

answers:

4

I have a program which places structures in a linked list based on the 'name' they have stored in them.

To find their place in the list, i need to figure out if the name im inserting is earlier or later in the alphabet then those in the structures beside it.

The names are inside the structures, which i have access to. I don't need a full comaparison if that is more work, even just the first letter is fine.

Thanks for the help!

+1  A: 

If you have two C strings, a and b, you can simply compare their first elements:

*a == *b

Where == can be any of the six relational operators.

Remember that with C strings, the char* points to the first character in the string.

James McNellis
don't forget to check for NULL
Andrey
+1  A: 

strcmp() compares two C strings and will tell you what order they're in, or if they're the same. If you don't care about case, you can use strcasecmp(). These functions won't compare any more of the strings than necessary to determine what order to return.

Carl Norum
Note, though, that strcasecmp is not standard C.
Arkku
+1  A: 

It's not clear to me what your question is, but something like this would work:

if (node1->name[0] <= node2->name[0]) {
  ...
} else {
  ...
}

This will compare the first letter of the name in each of the nodes.

RarrRarrRarr
+1  A: 

You can simply iterate through the list and insert the new element in the correct place based on comparisons you do while passing each element. The simplest case sensitive version can be done just by comparing the numeric values of the letters (e.g. a[0] < b[0]), or you can convert both to a common case if you want to be case-insensitive (see ctype.h). Or you can compare the whole words with strcmp.

Arkku