for (a = str; * a; a++) ...
This works by starting a pointer a
at the beginning of the string, until dereferencing a
is implicitly converted to false, incrementing a
at each step.
Basically, you'll walk the array until you get to the NUL terminator that's at the end of your string (\0
) because the NUL terminator implicitly converts to false - other characters do not.
Using the method above, how could I parse it and get the last integer of the string (2000), knowing that the last integer (2000) may vary.
You're going to want to look for the last space before the \0
, then you're going to want to call a function to convert the remaining characters to an integer. See strtol
.
Consider this approach:
- find the end of the string (using that loop)
- search backwards for a space.
- use that to call
strtol
.
-
for (a = str; *a; a++); // Find the end.
while (*a != ' ') a--; // Move back to the space.
a++; // Move one past the space.
int result = strtol(a, NULL, 10);
Or alternatively, just keep track of the start of the last token:
const char* start = str;
for (a = str; *a; a++) { // Until you hit the end of the string.
if (*a == ' ') start = a; // New token, reassign start.
}
int result = strtol(start, NULL, 10);
This version has the benefit of not requiring a space in the string.