Search code examples
carraysstringsortingcapitalization

Sorting an Array of strings with capital and lowercase letters in C


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


Solution

  • 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.