Reverse Words in a String

From Software Engineers Wiki
Jump to: navigation, search

Reverse the ordering of words in a string.

Answer #1

If the function gets an additional buffer to put the result to, it can find the word boundary and make copy of each words.

char *str_reverse_word_order(char *str, char *dst)
{
        char *head, *tail;
        char *cp = dst;

        /* find the end of the string */
        for (tail = str; *tail != '\0'; ++tail)
                ;
        --tail;

        for (;;) {
                /* find the end of the word. copy the white spaces */
                while (tail >= str && isspace(*tail))
                        *cp++ = *tail--;
                if (tail < str)
                        break;
                /* find the beginning of the word */
                for (head = tail; head >= str && !isspace(*head); --head)
                        ;
                ++head;
                /* copy the word */
                memcpy(cp, head, tail - head + 1);
                cp += tail - head + 1;
                /* prepare for next iteration */
                if (head == str)
                        break;
                tail = head - 1;
        }

        *cp = '\0';

        return dst;
}

Answer #2

If the function needs to work on the original string, and reverse the order in place, it can reverse the entire string first, then reverse each words again.

void str_reverse(char *head, char *tail)
{
        char tmp;

        while (head < tail) {
                tmp = *head;
                *head++ = *tail;
                *tail-- = tmp;
        }
}

char *str_reverse_word_order_in_place(char *str)
{
        char *head, *tail;

        /* reverse entire string */
        for (head = str, tail = str; *tail != '\0'; ++tail)
                ;
        str_reverse(head, --tail);

        /* reverse words */
        head = str;

        while (*head != '\0') {
                while (isspace(*head))
                        ++head;
                if (*head == '\0')
                        break;
                for (tail = head; *tail != '\0' && !isspace(*tail); ++tail)
                        ;
                --tail;
                str_reverse(head, tail);
                head = tail + 1;
        }

        return str;
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox