Skip to content

Instantly share code, notes, and snippets.

@ooade
Last active January 14, 2017 12:32
Show Gist options
  • Save ooade/9c888a1b934ec6a78577a872c2656b8f to your computer and use it in GitHub Desktop.
Save ooade/9c888a1b934ec6a78577a872c2656b8f to your computer and use it in GitHub Desktop.
My CS50 Hackerrank Solutions

Hello World! My solutions to the contest are posted here!

#include <cs50.h>
#include <string.h>
#include <stdio.h>
string append_suffix(int i);
int main(void)
{
char *data = get_string();
const char* s = " ";
char *token;
int i = 1;
if (data == NULL)
{
printf("There is no box");
return (0); // Stop the program;
}
token = strtok(data, s);
while (token != NULL)
{
if (strcmp(token, "cat") == 0)
{
// If cat is found, don't bother checking for others;
break;
}
token = strtok(NULL, s);
i++;
}
//get_string() returns NULL if no string is passed;
if (token != NULL)
{
printf("The cat is the %i%s item in the box", i, append_suffix(i));
}
else
{
printf("No cat yet");
}
}
string append_suffix(int i)
{
/* Check through 14 - 98;
we cant have 11st, 12nd or 13rd buh
we can have 21th, 22nd or 23rd
*/
if (i > 13 && i < 99)
{
i = i % 10;
}
switch (i)
{
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
string title_case(string str);
int main(void)
{
char* data = get_string();
printf("%s\n", title_case(data));
}
char* concat(char *s1, char *s2)
{
char *result = malloc(strlen(s1) + strlen(s2));
strcpy(result, s1);
strcat(result, s2);
return result;
}
string title_case(string str)
{
char* result = "";
char* del = " ";
char* token = strtok(str, del);
int i = 0;
while(token != NULL)
{
if (i == 0)
{
token[0] = toupper(token[0]);
}
if (
strcmp(token, "the") != 0 &&
strcmp(token, "of") != 0 &&
strcmp(token, "and") != 0 &&
strcmp(token, "but") != 0
)
{
token[0] = toupper(token[0]);
}
result = concat(result, token);
result = concat(result, " ");
token = strtok(NULL, del);
i++;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment