how would you parse the string, 1234567 into individual numbers?
+9
A:
char mystring[] = "1234567";
Each digit is going to be mystring[n] - '0'
.
Delan Azabani
2010-09-16 01:42:19
+3
A:
What Delan said. Also, it's probably bad practice for maintainability to use a ASCII dependent trickery. Try using this one from the standard library:
int atoi ( const char * str );
EDIT: Much better idea (the one above has been pointed out to me as being a slow way to do it) Put a function like this in:
int ASCIIdigitToInt(char c){
return (int) c - '0';
}
and iterate this along your string.
Sam Svenbjorgchristiensensen
2010-09-16 01:46:11
Good point, Sam. Using atoi makes it clearer what is intended.
Iain
2010-09-16 01:47:26
Very good point, this would be good for if you have the possibility of using the program on a non-ASCII/UTF-8 system. However, please take note that `atoi` takes a `char*`, or string, not a `char`, so you'll have to convert the individual character into a single-character string before it goes to `atoi`.
Delan Azabani
2010-09-16 01:47:34
Ok I fixed it. Cheers.
Sam Svenbjorgchristiensensen
2010-09-16 01:54:17
The characters `'0'` through `'9'` are guaranteed to be consecutive (it's a standard requirement on the implementation), so subtracting `'0'` from a character that you know is a digit is not ASCII-dependent trickery. (This is *not* the case for letters; A-Z and a-z are only guaranteed to be in increasing order, not consecutive.)
Zack
2010-09-16 01:57:04
There's no ASCII trickery in Delan's answer. The ISO standard mandates that the numeric characters are contiguous so `ch - '0'` is perfectly portable.
paxdiablo
2010-09-16 01:57:04
That's interesting, I didn't know that. At any rate, using the standard library functions still makes far clearer code so my recommendation still stands.
Sam Svenbjorgchristiensensen
2010-09-16 02:02:29
@Sam: subtracting `'0'` is a lot smaller, simpler, and more readable than copying the character into a separate array with null termination so you can pass it to `atoi`, not to mention probably 100 times faster. Your answer is just bad advice.
R..
2010-09-16 03:28:17
Oh. This stems from my mistake that atoi took a char not char*. Good point. Instead, write a simple one line function that does the `ch - '0'` stuff into a function called something meaningful like ASCIIdigitToInt. The compiler will inline it anyway so it won't be any slower.
Sam Svenbjorgchristiensensen
2010-09-16 03:57:27
+2
A:
Don't forget that a string in C is actually an array of type 'char'. You could walk through the array, and grab each individual character by array index and subtract from that character's ascii value the ascii value of '0' (which can be represented by '0').
Iain
2010-09-16 01:46:24