On 7 Jan, 16:29, jameskuyper <(EMail Removed)> wrote:
> Steve555 wrote:
> > Hi
>
> > I'm comparing two strings with strcmp(), but they might be words or
> > numbers. Is there a convenient way to handle number strings with strcmp
> > () such that 4 is less than 2300 for example, or do I have to manually
> > check if they're numbers and handle this case separately each time?
>
> If you want them sorted according to their numerical value, rather
> than as strings, then you have to calculate that numerical value. That
> means you have to actually determine whether they are numbers.
>
> Do you have any control over the content of those number strings? If
> all of your number strings represent positive integers, and if you can
> pad the strings with leading '0' characters to all be the same length
> (for instance, by using printf("%09u" ...) ), then strcmp() will order
> them the same way as their numerical value.
>
> You can also pad with blanks instead of '0' by using the '' flag
> rather than the '0' flag, but this only works if ' ' < '0'. That
> happens to be true in every encoding I'm familiar with, but it's not
> required by the C standard.
>
> Do the strings sometimes have a mixture of numbers and letters? If so,
> you'll have to decide how you want "4C" to sort relative to "20".
> There's lots of possible ways of answering that question, and the
> appropriate method of dealing with them depends upon the answer.
Thanks for all the advice, strnatcmp() will do the job nicely.
>Do you have any control over the content of those number strings? If
>all of your number strings represent positive integers, and if you can
>pad the strings with leading '0' characters to all be the same length
>(for instance, by using printf("%09u" ...) ), then strcmp() will order
>them the same way as their numerical value.
Yes, they're always positive integers, but how will printf("%09u" ...)
help, as they are already strings?
Did you mean convert them to longs, then back to strings? I see how
padding would help sort them, but using printf("%09u" ...) on strings
produces gibberish. (Sorry, I guess I've misunderstood you.)
Thanks
Steve
