-
-
Save CraigRodrigues/600c281cf7a216b7dccd2b4f405226c0 to your computer and use it in GitHub Desktop.
CS50x Coding Contest 2016 - Word Reverse
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 <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <ctype.h> | |
#include "cs50.h" | |
char* reverseString(char* s); | |
int main(void) { | |
char *str = malloc(sizeof(char *) * 200); | |
str = GetString(); //get input from user | |
char *temp = malloc(sizeof(char *) * 200); | |
int j = 0; | |
if (str == NULL) | |
return 1; | |
// loop through string copying to a temp string until a special character or space is found. | |
for (int i = 0; i < strlen(str); i++) | |
{ | |
if (isalnum(str[i])) | |
{ | |
temp[j] = str[i]; | |
j++; | |
if (i == strlen(str)-1) //this is a check to see if this is the last character | |
{ | |
reverseString(temp); // reverse temp string and print | |
printf("%s", temp); | |
j = 0; // reset back to beginning of temp array once we find a special character | |
memset(&temp[0], 0, sizeof(temp)); // clear temp array | |
} | |
} | |
else if (!isalnum(str[i])) | |
{ | |
reverseString(temp); // reverse temp string and print | |
printf("%s", temp); | |
printf("%c", str[i]); // print space/special character | |
j = 0; // reset back to beginning of temp array once we find a special character | |
memset(&temp[0], 0, sizeof(temp)); // clear temp array | |
} | |
} | |
free(str); //free memory | |
return 0; | |
} | |
char* reverseString(char* s) { | |
int length = 0, i = 0; | |
length = strlen(s); | |
char temp[1]; | |
for(i = 0; i < length/2; i++) | |
{ | |
*temp = s[i]; | |
s[i] = s[length-i-1]; | |
s[length-i-1] = *temp; | |
} | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Problems I encountered: