行程编码(atoi函数)
1 #include<iostream> 2 #include<string> 3 #include<vector> 4 using namespace std; 5 void jiema(string s) 6 { 7 cout << "解码之后为:" << endl; 8 for(int i = 0; i < s.size(); i++) 9 { 10 if(s[i + 1] == '*') 11 { 12 int j = i + 1; 13 int len = 0; 14 while(s[j + 1] >= 48 && s[j + 1] <= 57) 15 { 16 len++; 17 j = j + 1; 18 } 19 string temp = s.substr(i + 2, len); 20 int num = atoi(temp.c_str()); 21 for(int k = 0; k < num; k++) 22 { 23 cout << s[i]; 24 } 25 i = j; 26 } 27 else 28 { 29 cout << s[i]; 30 31 } 32 } 33 }
34 void bianma(string s) 35 { 36 vector<char>A; 37 int p = 1; 38 int j = 0; 39 for(; j < s.size();) 40 { 41 while(s[j] == s[j + 1] && j < s.size()) 42 { 43 p++; 44 j = j + 1; 45 } 46 if(p >= 4) 47 { 48 A.push_back(s[j]); 49 A.push_back('*'); 50 A.push_back(p); 51 p = 1; 52 j = j + 1; 53 } 54 else if(p < 4) 55 { 56 for(int k = 0; k < p; k++) 57 { 58 A.push_back(s[j]); 59 } 60 p = 1; 61 j = j + 1; 62 } 63 } 64 cout << "编码之后为:" << endl; 65 for(int b = 0; b < A.size(); b++) 66 { 67 if(A[b] >= 0 && A[b] <= 9) 68 cout << int(A[b]); 69 else 70 cout << A[b]; 71 } 72 cout << endl; 73 cout << "压缩比为:" << endl; 74 double y = double(A.size()) / s.size(); 75 cout << y << endl; 76 } 77 void main() 78 { 79 cout << "请输入代码:①代码中含有数字表示需要解码解压缩②代码中不含数字表示需要编码压缩" << endl; 80 string s; 81 for(; cin >> s;) 82 { 83 int i = 0; 84 for(; i < s.size(); i++) 85 { 86 if(s[i] >= 48 && s[i] <= 57) //解码 87 { 88 jiema(s); 89 break; 90 } 91 } 92 if(i == s.size()) 93 { 94 bianma(s); 95 } 96 } 97 }