Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
A reverse-words-in-place C version:
#include <stdio.h> #include <stdlib.h> char * readlinef(FILE *stream) { int buffer_len = 0; int len = 0; char *buffer; while (1) { int c = fgetc(stream); switch (c) { case '\n': if (!len) continue; case EOF: if (buffer) buffer[len] = '\0'; return buffer; default: if (len >= buffer_len) { buffer_len = buffer_len * 2 + 100; buffer = (char *)realloc(buffer, buffer_len + 1); } buffer[len++] = c; } } } void reverse(char *start, char *end) { while (start < --end) { char tmp = *end; *end = *start; *(start++) = tmp; } } char * skip_spaces(char *p) { while (isspace(*p)) p++; return p; } char * skip_word(char *p) { while (*p && !isspace(*p)) p++; return p; } int main(int argc, char *argv[]) { char *line; while (line = readlinef(stdin)) { char *start = line; while (1) { char *word_start = skip_spaces(start); char *word_end = skip_word(word_start); if (word_start == word_end) { if (start != line) start--; break; } reverse(start, word_end); start += word_end - word_start; if (*start == '\0') break; start++; } reverse(line, start); *start = '\0'; fprintf(stdout, "%s\n", line); free(line); } }

In reply to Re^2: Five Ways to Reverse a String of Words (ANSI C version) by salva
in thread Five Ways to Reverse a String of Words (C#, Perl 5, Perl 6, Ruby, Haskell) by eyepopslikeamosquito

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others imbibing at the Monastery: (3)
    As of 2021-01-16 03:00 GMT
    Find Nodes?
      Voting Booth?