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);
}
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|