views:

126

answers:

3

Is there a way to sort an array of strings in alphabetical order where the strings contain both capital and lowercase letters?

Because capital letters have a lower ASCII value so functions like strcmp would always show that it is before a lower case letter. For example, lets say we wanted to sort "ABCD", "ZZZZ", "turtle", "JAVA", "water".

When using functions like strcmp to sort these strings, it becomes:

ABCD JAVA ZZZZ turtle water

when it should be:

ABCD JAVA turtle water ZZZZ

+2  A: 

Try strcoll(3).

Carl Norum
How do I use this? From what I understand, it calls strcmp unless there is a locale set... but I don't know what a locale is.
DemonicImpact
strcoll works case-sensitive like strcmp, not a solution for your question
@user411313, that depends on the locale you have set.
Carl Norum
@DemonicImpact: Just calling `setlocale(LC_COLLATE, "");` will set the string collation locale to that appropriate for the user's language.
caf
+1  A: 

Use qsort with either strcasecmp or strcoll as the compare function.

strcasecmp is likely to be faster, but strcoll is more flexible and uses the programs locale so that non-ASCII strings work.

nategoose
strcasecmp is not C89/C99 -> is not ANSI C
+1  A: 

a simple own solution in strictly C89 should help:

#include <ctype.h>
#include <string.h>

int strcmpIgnoreCase(const char *a,const char *b)
{
  while( *a && *b )
  {
    register r=tolower(*a)-tolower(*b);
    if( r )
      return r;
    ++a;
    ++b;
  }
  return tolower(*a)-tolower(*b);
}
tolower **needs** an `unsigned char`. To be portable, your code should cast the argument: `tolower((unsigned char)*a)`. *Oh ... and specify `int` for `register r`: that way your code is also `C99`-compatible.*
pmg