summaryrefslogtreecommitdiff
path: root/hw4/problem5.c
blob: 31a4916827f76a0cd03aab207fbd20099c0de1d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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;
}