juli (caladri) wrote in dailysrc,
juli
caladri
dailysrc

do not mix with word-palindromes

Ok, ok, it's another common interview question, but the answer that I like is ever so slightly unusual because it's more generic, and actually a bit easier to write out for the first time, because of how the logic is broken out.



#include <stdio.h>
#include <string.h>

/*
 * Reverse the letters in the string passed in as buf.
 */
static void
rev(char *buf)
{
        char c, *p;

        p = buf + strlen(buf);
        while ((c = *buf) != '\0' && p-- > buf) {
                *buf++ = *p;
                *p = c;
        }
}

/*
 * Call a function for each word in a string.
 */
static void
foreach_word(char *buf, void (*rf)(char *))
{
        char c, *p, *s;

        for (p = buf; *p != '\0'; p++) {
                for (s = p; *s != '\0' && *s != ' '; s++)
                        continue;
                if ((c = *s) != '\0')
                        *s-- = '\0';
                (*rf)(p);
                if (c == '\0')
                        break;
                *++s = c;
                p = s;
        }
}

/*
 * Reverse the words in a string.
 */
static void
wordrev(char *buf)
{
        /*
         * First, reverse the string.
         */
        rev(buf);

        /*
         * Second, reverse each word.
         */
        foreach_word(buf, rev);

        printf("%s\n", buf);
}

int
main(void)
{
        char string[] = "son i am able she said though you scare me watch said i beloved i said watch me scare you though said she able am i son";
        wordrev(string);
        return (0);
}

Subscribe
  • Post a new comment

    Error

    default userpic

    Your IP address will be recorded 

  • 0 comments