Right String

A recent web page programming puzzle reminded me of an old BASIC language function, RIGHT$. The “right-string” function returns the rightmost n characters from a string. Such a function would have helped me greatly in my web page programming task.

The problem I was trying to solve was to fetch a filename from a pathname. The filename is the right-most part of the pathname, preceded by a slash (or backslash in Windows). For example:

http://c-for-dummies.com/images/c.png

In the above web address (which is a fancy pathname) c.png is the filename I wanted. I could have coded a filename-extractor utility, one that scans a string for the last part, the filename, and generates that output. Instead, I recalled the old RIGHT$ function and decided to craft it instead. That’s because the filename I wanted was always going to be the same length; what changed was the address. For example:

http://c-for-dummies.com/images/c.png
http://www.c-for-dummies.com/images/c.png
/c-for-dummies.com/images/c.png

Recalling from my youthful BASIC language programming days, if I used the RIGHT$ command on each of the above strings, I could easily extract the c.png filename. The format for RIGHT$ (in BASIC) is:

RIGHT$(var$,n)

where var$ is a string variable or constant, and n is the number of characters to extract from the right end of var$.

Your task for this month’s Exercise is to code a right() function. It takes two arguments, a string and a size, and returns a pointer to the position in string relative to value the string’s end (on the right side). For example:

right("http://c-for-dummies.com/images/c.png",4);

returns the string "c.png", or a pointer to that location within the string constant, shown above.

You must process the three strings listed earlier and return the filename c.png as the result. Here’s sample output:

http://c-for-dummies.com/images/c.png -> c.png
http://www.c-for-dummies.com/images/c.png -> c.png
/c-for-dummies.com/images/c.png -> c.png

I can think of two ways to craft the right() function. Click here to view my solutions. Before doing so, please try this Exercise on your own.

Leave a Reply