3

Possible Duplicate:
Natural sort in C - “array of strings, containing numbers and letters”

When sorting strings in C with qsort and strcmp I have the problem that alphanumeric entries, typically strings ending with numbers, are being sorted oddly like this:

  • Entry1
  • Entry12
  • Entry2

The desired behavior is this:

  • Entry1
  • Entry1_new
  • Entry2
  • Entry12

What is the easiest way to do this?

Thanks

Community
  • 1
  • 1
Chris
  • 981
  • 4
  • 14
  • 29
  • Use leading zeros in all your numerical portions: Entry01, Entry01_new, Entry02, Entry12, etc. Otherwise you'll have to dump `strcmp` and roll your own string comparison function that recognizes numerical strings as integer values. – John Bode Jul 27 '11 at 17:08

1 Answers1

1

There's nothing odd about the sort; '1' comes before '2', so any string that has 'Entry1' will come before any string that has 'Entry2'. That's just the way strcmp is defined. If you desire a different sort order, you can always write a different sort function.

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117
  • It's not the sort function that needs help, it's the comparison function. – Mark Ransom Jul 27 '11 at 17:00
  • Thanks for your answers, I know that this is the normal behavior of strcmp. My question is what is the easiest way to achieve the desired behavior. – Chris Jul 28 '11 at 06:13