1 /* -*- mode: c; c-file-style: "k&r" -*-
3 strnatcmp.c -- Perform 'natural order' comparisons of strings in C.
4 Copyright (C) 2000, 2004 by Martin Pool <mbp sourcefrog net>
6 This software is provided 'as-is', without any express or implied
7 warranty. In no event will the authors be held liable for any damages
8 arising from the use of this software.
10 Permission is granted to anyone to use this software for any purpose,
11 including commercial applications, and to alter it and redistribute it
12 freely, subject to the following restrictions:
14 1. The origin of this software must not be misrepresented; you must not
15 claim that you wrote the original software. If you use this software
16 in a product, an acknowledgment in the product documentation would be
17 appreciated but is not required.
18 2. Altered source versions must be plainly marked as such, and must not be
19 misrepresented as being the original software.
20 3. This notice may not be removed or altered from any source distribution.
23 /* Modified by Guillaume Chazarain in order to be integrated in GLiv */
30 #include "strnatcmp.h"
33 static int compare_right(const char *a
, const char *b
)
37 /* The longest run of digits wins. That aside, the greatest
38 value wins, but we can't know that it will until we've scanned
39 both numbers to know that they have the same magnitude, so we
40 remember it in BIAS. */
43 return isdigit(*b
) ? -1 : bias
;
44 else if (!isdigit(*b
))
52 } else if (!*a
&& !*b
)
60 static int compare_left(const char *a
, const char *b
)
62 /* Compare two left-aligned numbers: the first to have a
63 different value wins. */
66 return !isdigit(*b
) - 1;
67 else if (!isdigit(*b
))
79 int strnatcmp(const char *a
, const char *b
)
83 int fractional
, result
;
90 /* skip over leading spaces or zeros */
97 /* process run of digits */
98 if (isdigit(ca
) && isdigit(cb
)) {
99 fractional
= (ca
== '0' || cb
== '0');
102 if ((result
= compare_left(a
+ ai
, b
+ bi
)) != 0)
105 if ((result
= compare_right(a
+ ai
, b
+ bi
)) != 0)
111 /* The strings compare the same. Perhaps the caller
112 will want to call strcmp to break the tie. */