Pulling Numbers from a String

Difficulty: ★ ★ ★ ★

Rarely in your programming journey will you encounter a situation where the data you need just pops up fresh, exactly the way you want it. The best situation is where the data is somehow formatted, which makes finding the tidbit you want easier. But often the data is unformatted, which makes fetching that one useful morsel a bit tricky.

Consider the following string:

abc10=13!260;1m

This data could be a command or perhaps a report. Regardless, the parts you want are the values: 10, 13, 260, and 1. I remember performing such a programming task on directory listings when I first learned to code. But the advantage of a directory listing is that the columns are distinct and predictable. Therefore, the code relies upon data being available at specific offsets. Easy. Such consistency shouldn’t be assumed for this example.

Your task is to write a function, extract(). Its job is to locate the first bit of numerical data in a string. For example, if you call extract() on the above string, it returns the location (as a pointer) of the 1 after abc. This address is then used to convert the characters 10 into an integer. (Converting the string into an integer isn’t part of the extract() function.)

But wait! There’s more . . .

Your task for this exercise isn’t just to yank out the first number found and convert it into a string. No, you must code the extract() function so that it can be called repeatedly, each time extracting the next value from the same string until it’s exhausted all possible values. The sample output from my solution reflects this condition:

10
13
260
1

Remember, the extract() function doesn’t know where a number exists within the string. Its job is to return the address of the first digit found, then to be called again and again to find subsequent digits. When the string is exhausted, the function returns NULL.

I have a reason for presenting this exercise, which will will become apparent later this month. For now, try writing the extract() function on your own before peeking at my solution, which I’ll post in a week.

Leave a Reply