Say I have a string like ab234cid*(s349*(20kd
and I want to extract all the numbers 234, 349, 20
, what should I do ?
You can use sscanf here if you know the number of items you expect in the string: char const *s = "10 22 45 67 89"; sscanf(s, "%d %d %d %d %d", numbers, numbers+1, numbers+2, numbers+3 numbers+4);
Print out the integers in the string. Run one for loop to read character by character. First, convert this string to an array of characters by using the toCharArray() method and then read each character ony by one using a for loop. Check if the character is a number or not using the isDigit method.
You can do it with strtol
, like this:
char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
// Found a number
long val = strtol(p, &p, 10); // Read number
printf("%ld\n", val); // and print it.
} else {
// Otherwise, move on to the next character.
p++;
}
}
Link to ideone.
A possible solution using sscanf()
and scan sets:
const char* s = "ab234cid*(s349*(20kd";
int i1, i2, i3;
if (3 == sscanf(s,
"%*[^0123456789]%d%*[^0123456789]%d%*[^0123456789]%d",
&i1,
&i2,
&i3))
{
printf("%d %d %d\n", i1, i2, i3);
}
where %*[^0123456789]
means ignore input until a digit is found. See demo at http://ideone.com/2hB4UW .
Or, if the number of numbers is unknown you can use %n
specifier to record the last position read in the buffer:
const char* s = "ab234cid*(s349*(20kd";
int total_n = 0;
int n;
int i;
while (1 == sscanf(s + total_n, "%*[^0123456789]%d%n", &i, &n))
{
total_n += n;
printf("%d\n", i);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With