I was wondering if somebody could explain me how pointers and string parsing works. I know that I can do something like the following in a loop but I still don’t follow very well how it works.
for (a = str; * a; a++) ...
For instance, I’m trying to get the last integer from the string. if I have a string as const char *str = "some string here 100 2000";
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.
Thanks
This works by starting a pointer
aat the beginning of the string, until dereferencingais implicitly converted to false, incrementingaat 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.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. Seestrtol.Consider this approach:
strtol.–
Or alternatively, just keep track of the start of the last token:
This version has the benefit of not requiring a space in the string.