Skip to content

Instantly share code, notes, and snippets.

@manashmandal
Created July 30, 2016 03:47
Show Gist options
  • Save manashmandal/6b6cc26bc74314a2a47cec2d718e2900 to your computer and use it in GitHub Desktop.
Save manashmandal/6b6cc26bc74314a2a47cec2d718e2900 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include "cs50.h"
#define S_BUFFER 20
#define L_BUFFER 900
#define empty '\0'
#define print_number(x) printf("%d", x)
#define print_string(x) printf("%s", x)
void reverse(char str[], int begin, int end);
//int words(const char sentence[ ])
//{
// int counted = 0; // result
// // state:
// const char* it = sentence;
// int inword = 0;
// do switch(*it) {
// case '\0':
// case ' ': case '\t': case '\n': case '\r': // TODO others?
// if (inword) { inword = 0; counted++; }
// break;
// default: inword = 1;
// } while(*it++);
// return counted;
//}
int words(char sentence[]){
int i;
int wordcount = 0;
for (i = 0; i < strlen(sentence), i+1 < strlen(sentence); i++){
if (sentence[i] == ' ' && sentence[i-1] != ' '){
wordcount++;
} else if (ispunct(sentence[i]) && sentence[i-1] != ' '){
wordcount++;
} else if (ispunct(sentence[i]) && sentence[i+1] != ' '){
wordcount++;
}
}
if (strlen(sentence) != 0) wordcount++;
return wordcount;
}
//Array for holding the indices for beginning and ending of a word
int *word_begin;
int *word_end;
void stamp_words(char input[])
{
int i;
int begin_index = 0;
int end_index = 0;
//Stores the first index
if (input[0] != empty){
word_begin[begin_index] = 0;
begin_index++;
}
for (i = 0; i < strlen(input); i++){
if ((input[i] == ' ' && input[i-1] != ' ') || (ispunct(input[i]) && input[i-1] != ' ')) {
word_end[end_index] = i-1;
end_index++;
} if ((input[i] == ' ' && input[i+1] != ' ') || (ispunct(input[i]) && input[i-1] != ' ')){
word_begin[begin_index] = i+1;
begin_index++;
}
}
char another[L_BUFFER];
strcpy(another, input);
for (i = 0; i < words(input); i++){
// printf("begin [%d] = %d\n", i, word_begin[i]);
// printf("end [%d] = %d\n", i, word_end[i]);
// printf("------------------------\n");
reverse(another, word_begin[i], word_end[i]);
}
// reverse(another, word_begin[0], word_end[0]);
puts(another);
}
void reverse(char str[], int begin, int end)
{
int i = begin;
int j = end;
for (i = begin, j = end; i <= j; i++, j--){
char t = str[i];
str[i] = str[j];
str[j] = t;
}
}
int main(void)
{
string in = GetString();
char content[L_BUFFER];
strcpy(content, in);
int word_count = words(content);
//Allocate memory for holding the indices
word_begin = (int*) malloc(sizeof(int) * word_count);
word_end = (int*) malloc(sizeof(int) * word_count);
char delimiter[] = {' ', '\0'};
strcat(content, delimiter);
stamp_words(content);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment