summaryrefslogtreecommitdiff
path: root/hw4/problem5.c
diff options
context:
space:
mode:
Diffstat (limited to 'hw4/problem5.c')
-rw-r--r--hw4/problem5.c84
1 files changed, 84 insertions, 0 deletions
diff --git a/hw4/problem5.c b/hw4/problem5.c
new file mode 100644
index 0000000..31a4916
--- /dev/null
+++ b/hw4/problem5.c
@@ -0,0 +1,84 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+void printArray(char **words, int wordcount){
+ for(int i = 0; i < wordcount; i++)
+ printf("%s\n",words[i]);
+}
+void proper(char *word){
+ word[0] = toupper(word[0]);
+}
+int string2array(char *inString, char **wordarray){
+ const char whitespace[] = " ";
+ char **cursor = wordarray;
+ int ret = 0;
+ char *this = NULL;
+ while(1){
+ this = strtok(inString,whitespace);
+ if(this == NULL)
+ break;
+ char *dest = strcpy(wordarray[ret],this);
+ inString = NULL;
+ ret++;
+ }
+ return ret;
+}
+void getString(char *in, int buffer){
+ char *c = in;
+ for(; c < in + buffer; c++){
+ *c = getchar();
+ if(*c == EOF)
+ break;
+ }
+ *c = '\0';
+}
+
+struct Sentence {
+ char string[50];
+ char *words[10];
+ int wordCount;
+};
+
+void bubblesort(Sentence s){
+ while(1){
+ int any_out_of_order = 0;
+ for(int i = 0; i < wordCount - 1; i++){
+ if(strcmp(s.words[i], s.words[i+1]) > 0){ //we found some words out of order
+ any_out_of_order = 1;
+ //swap
+ char *tmp = s.words[i];
+ s.words[i] = s.words[i+1];
+ s.words[i+1] = tmp;
+ }
+ }
+ //If we go over the whole array, and no one is out of order,
+ //we're done
+ if(any_out_of_order == 0)
+ break;
+ }
+}
+
+/*
+ a. Store input into the sentence string,
+ b. Parse the string into an array of words and store the number of words found,
+ c. Proper case each word in the sentence,
+ d. and print out the proper cased sentence
+*/
+int main(int argc, char **argv){
+ struct Sentence s;
+ for(int i = 0; i < 10; i++)
+ s.words[i] = malloc(sizeof(char) * 50);
+ s.wordCount = 0;
+ getString(s.string,50);
+ s.wordCount = string2array(s.string, s.words);
+ for(int i = 0; i < 10; i++)
+ proper(s.words[i]);
+ printf("Before:\n");
+ printArray(s.words,s.wordCount);
+ bubblesort(s);
+ printf("After:\n");
+ printArray(s.words,s.wordCount);
+ return 0;
+}