Created
December 30, 2019 13:14
-
-
Save DarkSuniuM/28eef9833ab6804b76f071a56ba682c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
char * reverseWords(const char *text); | |
char * reverseWord(char *word); | |
int main () { | |
char *text = "Hello World"; | |
char *result = reverseWords(text); | |
printf("%s == %s\n", result, "olleH dlroW"); | |
printf("%d\n", (result == "olleH dlroW")); | |
return 0; | |
} | |
char * | |
reverseWords (const char *text) { | |
int i, j; | |
size_t len = strlen(text); | |
size_t text_size = len * sizeof(char); | |
char *output; | |
char *temp_word; | |
char temp_char; | |
output = (char *) malloc (text_size + 1); | |
for(i = 0; i < len; i++) { | |
if (text[i] == ' ') { | |
output[i] = ' '; | |
} | |
if (text[i] == '\0') { | |
break; | |
} | |
temp_word = (char *) malloc (text_size + 1); | |
j = 0; | |
while((text[i + j] != ' ') && (text[i + j] != '\0')) { | |
temp_char = (char) text[i+j]; | |
strcat(temp_word, &temp_char); | |
j++; | |
} | |
strcat(output, reverseWord(temp_word)); | |
if (text[i+j] == ' ') | |
strcat(output, " "); | |
free(temp_word); | |
i += j; | |
} | |
return strstr(output, "\0"); | |
// return output; | |
} | |
char * | |
reverseWord (char *word) { | |
int i, j; | |
size_t len = strlen(word); | |
char *output; | |
output = (char *) malloc (len + 1); | |
j = 0; | |
for(i = (len - 1); i >= 0; i--) { | |
output[j++] = word[i]; | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment