Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CS50x Coding Contest 2016 - Word Reverse
#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;
}
@CraigRodrigues

This comment has been minimized.

Copy link
Owner Author

commented Aug 1, 2016

Problems I encountered:

  1. I needed a way to clear my temp array after each swap. Looked that up and got an answer to just clear the memory which worked well.
  2. Initially used scanf instead of GetString. Scanf only goes up the first space character which is a problem.
  3. If my string didn't end in a special character it wouldn't work, so I needed to add a check to see if we were on the last index of the string and then do the reversing and printing if that was the case.
  4. I didn't put in a check for a NULL string.
  5. I didn't realize that it wasn't just alpha characters that needed to be switched, but alphanumeric. So instead of isalpha you have to use isalnum.
  6. I used my initial reverseString function I created for leetcode problem.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.