c - Count how many integer values separated by spaces are in a given string -
i want make function that, given character string containing (unsigned) integer values separated spaces, gives me number of values in string:
int conta_coords(char *args) { char *pal; int k=0; pal = strtok (args," "); while (pal != null) { k++; pal =strtok (null," "); } return k; }
this function won't give me right number. can me?
in way won't give correct number? here's code embedded sscce (short, self-contained, correct example).
#include <string.h> #include <stdio.h> extern int conta_coords(char *str); int conta_coords(char *args) { char *pal; int k=0; pal = strtok (args," "); while (pal != null) { k++; pal =strtok (null," "); } return k; } int main(void) { char data[] = "1 23 456 7890 12345"; printf("data: %s\n", data); printf("number: %d\n", conta_coords(data)); printf("data split: %s\n", data); return 0; }
output:
$ ./cntnum data: 1 23 456 7890 12345 number: 5 data split: 1 $
that looks correct me. note, though, original string has been chopped pieces. also, if had passed read-only string (string literal), might have gotten different results, because strtok()
modifies data works on, string literals aren't modifiable (and may core dump out of trying modify it). example:
printf("number: %d\n", conta_coords(" 1 23 45 67 99 "));
this gives me 'bus error' (and give core dump if weren't disabled).
here's alternative implementation works on constant strings not modifying searched string @ all, using much-underrated c89 standard functions strspn()
, strcspn()
:
#include <string.h> #include <stdio.h> extern int conta_coords(const char *str); int conta_coords(const char *str) { const char digits[] = "0123456789"; const char *ptr = str; int k = 0; int n = strcspn(ptr, digits); while (ptr[n] != '\0') { ptr += n; n = strspn(ptr, digits); if (n > 0) k++; ptr += n; n = strcspn(ptr, digits); } return k; } int main(void) { char data[] = "1 23 456 7890 12345"; printf("data: %s\n", data); printf("number: %d\n", conta_coords(data)); printf("data unsplit: %s\n", data); printf("number: %d\n", conta_coords(" 1 23 45 67 99 ")); return 0; }
output:
data: 1 23 456 7890 12345 number: 5 data unsplit: 1 23 456 7890 12345 number: 5
note 1 legitimate criticism of not demand integers separated blanks (so more accurate characterization of 'count how many sequences of 1 or more contiguous digits (separated 1 or more non-digits) appear in given string'). original code can criticized on similar grounds: counts number of sequences of consecutive non-blanks, separated 1 or more blanks, appear in given string. can refine implementation, wary of how deal erroneously formatted data , report problems.
Comments
Post a Comment