[1+1=2]
OneAndOneIs2

Sat, May 26, 2007

[Link][Icon]K&R 4.1 - I wasn't going to bother :(

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.

[More:]

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;
}
Leave a comment • Categories: Omni, Programming

Comments:

No Comments for this post yet...

Leave a comment:

Your email address will not be displayed on this site.
Your URL will be displayed.

Allowed XHTML tags: <p, ul, ol, li, dl, dt, dd, address, blockquote, ins, del, span, bdo, br, em, strong, dfn, code, samp, kdb, var, cite, abbr, acronym, q, sub, sup, tt, i, b, big, small>
(Line breaks become <br />)
(Set cookies for name, email and url)
(Allow users to contact you through a message form (your email will NOT be displayed.))

Categories

August 2008
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

Search

Misc

XML Feeds

What is this?
eXTReMe Tracker

Valid XHTML 1.0 Transitional

Valid CSS!

[Valid RSS feed]

powered by
b2evolution

blank