|
Sat, May 26, 2007
![[Link]](http://geekblog.oneandoneis2.org/img/chain_link.gif)
They give you the function "strindex" that basically scans a line for a pattern, grep-like, and returns the location of the first occurrence of the pattern.
Then they tell you to write "strrindex" to return the position of the RIGHTMOST occurrence of the pattern - i.e. if it occurs twice, they want the position of the second occurrence.
I was going to take their code and modify it by adding variables to make a note of each time a pattern was found. But then I thought "Why not just start at the right and work leftwards? Then I only have to look for the first pattern."
So I sat down with pen & paper and worked out the logic. And then it seemed silly NOT to go ahead and write it to test it worked.
Took a few more scribblings to work out the exact logic because of the numbering that applies to strings: "abc" is a four-character string because of the '\0' at the end, but the position numbers of the four-character string only go up to 3 because numbering starts at zero, and so confusion can happen..
But once I got that sorted, and I'd slapped myself for using [i] instead of [i++] with the result that I had an infinite loop, the code worked flawlessly. To my surprise, it must be said.
int strrindex(char s[], char t[])
{
int i, j, k, slength, tlength;
slength = 0;
tlength = 0;
/* Find the length of the s and t strings */
i = 0;
while (t[i++] != '\0')
++tlength;
i = 0;
while (s[i++] != '\0')
++slength;
k = 1;
/* Start from the right and work left */
for (i = slength; k > 0 && i > 0; i--)
/* Compare t to s until we have a match */
for (j=(i-1), k=tlength; k > 0 && s[j]==t[k-1]; j--,k--)
;
if (k == 0)
return (j+1);
else
return -1;
} No Comments for this post yet...
| Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|
| << < | > >> | |||||
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |