comparison libutil/numstring.c @ 3:d712d518059e

libutil: add functions for number string parsing/preening
author Mychaela Falconia <falcon@freecalypso.org>
date Sun, 26 Jun 2022 09:50:39 -0800
parents
children
comparison
equal deleted inserted replaced
2:b1c364729a93 3:d712d518059e
1 /*
2 * Utility functions for number string initial parsing or preening.
3 * grok_number_string() checks whether or not a user-supplied string
4 * argument is fully numeric (with possibility of allowing hyphens),
5 * and returns the number of digits. dehyphen_number_string() copies
6 * a possibly-hyphenated number string to a new buffer with all hyphens
7 * taken out.
8 */
9
10 #include <ctype.h>
11
12 grok_number_string(str, allow_hyphen)
13 char *str;
14 {
15 char *cp;
16 int c, n, last_hyphen;
17
18 n = 0;
19 last_hyphen = 0;
20 for (cp = str; *cp; ) {
21 c = *cp++;
22 if (isdigit(c)) {
23 n++;
24 last_hyphen = 0;
25 } else if (c == '-') {
26 if (!allow_hyphen || !n || last_hyphen)
27 return(-1);
28 last_hyphen = 1;
29 } else
30 return(-1);
31 }
32 if (last_hyphen)
33 return(-1);
34 return n;
35 }
36
37 dehyphen_number_string(src, dest)
38 char *src, *dest;
39 {
40 char *cp, *dp;
41 int c;
42
43 dp = dest;
44 for (cp = src; *cp; ) {
45 c = *cp++;
46 if (isdigit(c))
47 *dp++ = c;
48 }
49 *dp = '\0';
50 }