-
Notifications
You must be signed in to change notification settings - Fork 0
/
comma.cpp
132 lines (115 loc) · 2.86 KB
/
comma.cpp
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <iostream>
#include <istream>
#include <string>
using namespace std;
int num_words(string str);
void add_commas(string &str);
// finds commas in the pargraph and returns the words previous and next to it.
void get_words(int i, string &str);
// adds a comma before or after (where) a give `word` in a `paragraph`
void add_commas_to(string ¶graph, string word, char where);
// value to indicate whether or not you should perform the algorithm again.
int sentinel = 1;
int main(void)
{
string paragraph;
// get a string (min-length: 2) from the user
do
{
getline(cin, paragraph);
} while (paragraph.length() < 2);
// need to store a copy to manipulate it.
string paragraph_copy = paragraph;
// Number of words in the paragraph
int len = num_words(paragraph);
do
{
add_commas(paragraph);
} while (sentinel == 1);
cout << paragraph << endl;
return 0;
}
int num_words(string str)
{
int len = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ' || (str[i] == '.' && str[i + 1] == ' '))
{
len++;
}
}
return len;
}
void add_commas(string ¶graph)
{
for (int i = 0, n = paragraph.length(); i < n; i++)
{
if (paragraph[i] == ',')
{
// get the before and after words.
get_words(i, paragraph);
}
}
}
void get_words(int i, string &str)
{
// or store results in global array with not duplicates.
int j = i;
while (str[j - 1] != ' ' && (j - 1) != -1)
{
j--;
}
// make a variable for it
string prev;
// get the previous word
for (int k = j; k < i; k++)
{
prev.push_back(str[k]);
}
add_commas_to(str, prev, 'a');
// get the next word
int end = i + 1;
while (str[end + 1] != ' ' && str[end + 1] != '.')
{
end++;
}
// next word variable
string next;
for (int k = i + 2; k < end + 1; k++)
{
next.push_back(str[k]);
}
add_commas_to(str, next, 'b');
// store into global array;
// TODO
}
void add_commas_to(string ¶graph, string word, char where)
{
size_t found = paragraph.find(word);
int k = 0;
while (found != -1 && found < paragraph.length() - word.length())
{
if (where == 'b')
{
if (paragraph[found - 2] != ',' && paragraph[found - 2] != '.')
{
k = 1;
paragraph.insert(found - 1, ",");
}
}
else if (where == 'a')
{
if (paragraph[found + word.length()] != ',' && paragraph[found + word.length()] != '.')
{
k = 1;
paragraph.insert(found + word.length(), ",");
}
}
found = paragraph.find(word, found + word.length());
}
if (k == 0)
{
sentinel = 0;
}
}