This repository was archived by the owner on May 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
66 lines (56 loc) · 1.68 KB
/
Copy pathmain.cpp
File metadata and controls
66 lines (56 loc) · 1.68 KB
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
#include <iostream>
#include <sstream>
using std::cout;
using std::endl;
using std::ostringstream;
void compress(char* string){
// Get length of original string.
int length = 0;
char* start = string;
while(*start != '\0'){
length++;
start++;
}
char* newString = new char[length];
int newLength = 0;
for(int i = 0; i < length; i++){
// Character to check repeats.
char current = *(string + i);
// Find number of occurences.
int occurences = 1;
char* repeatFinder = (string + i + 1);
while(*repeatFinder == current){
occurences++;
repeatFinder++;
}
// Move ahead if there were extra occurences.
i += occurences - 1;
// Return if compressed string longer than original string.
int lengthExtension = 2;
int divided = occurences;
while((divided / 10) > 0){
lengthExtension++;
divided /= 10;
}
if(newLength + lengthExtension >= length)
return;
// Add to new string.
newString[newLength] = current;
ostringstream converter;
converter << occurences;
memcpy(newString + newLength + 1, converter.str().c_str(), (occurences % 10));
newLength += lengthExtension;
}
// Reset old string
for(int i = 0; i < length; i++){
string[i] = '\0';
}
memcpy(string, newString, newLength);
delete newString;
}
int main(int argc, char* argv[]){
char testString [18] = {0};
memcpy(testString, "aaabbbcgoodjooooo", 17);
compress(testString);
cout << testString << endl;
}