Skip to content

Instantly share code, notes, and snippets.

@fsouza
Last active December 10, 2015 09:38
Show Gist options
  • Save fsouza/4415624 to your computer and use it in GitHub Desktop.
Save fsouza/4415624 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct substring
{
char *inner;
int lower, upper;
};
void
set_value(struct substring *s, char *v)
{
s->inner = v;
s->lower = 0;
s->upper = strlen(v);
}
int
_find_space(struct substring s)
{
int i;
for(i = s.upper - 1; i >= s.lower; --i) {
if(s.inner[i] == ' ') {
return i;
}
}
return -1;
}
// This function assumes str has space to acommodate s.
void
subconcat(struct substring s, char *str)
{
int i, j = strlen(str);
for(i = s.lower; i < s.upper; ++i, ++j) {
str[j] = s.inner[i];
}
if(s.lower > 0 && s.inner[s.lower - 1] == ' ') {
str[j++] = ' ';
}
str[j] = '\0';
}
int
reverse(int n, char **input, char **output)
{
int i, index;
struct substring s;
for(i = 0; i < n; ++i) {
output[i][0] = '\0';
}
for(i = 0; i < n; ++i) {
index = -1;
set_value(&s, input[i]);
do {
if(index >= 0) {
s.upper = index;
}
index = _find_space(s);
s.lower = index + 1;
subconcat(s, output[i]);
s.lower = 0;
} while(index >= 0);
}
return 0;
}
void
readline(char *str)
{
char c;
int i;
for(i = 0; (c = getchar()) != EOF && c != '\n'; ++i) {
str[i] = c;
}
str[i] = '\0';
}
int
main(void)
{
int i, n;
char **words, **output;
scanf("%d\n", &n);
words = (char **)malloc(n * sizeof(char *));
output = (char **)malloc(n * sizeof(char *));
for(i = 0; i < n; ++i) {
words[i] = (char *)malloc(n * n *sizeof(char));
readline(words[i]);
output[i] = (char *)malloc(n * n *sizeof(char));
}
reverse(n, words, output);
for(i = 0; i < n; ++i) {
printf("Case #%d: %s\n", i+1, output[i]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment