c++编码解码字符串
时间: 2023-11-27 19:48:23 浏览: 86
以下是一个C++编码解码字符串的例子:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 编码字符串
string encodeString(const string& str) {
string res = "";
for (char c : str) {
if (isdigit(c)) {
res += c;
} else {
res += to_string((int)c);
}
}
return res;
}
// 解码字符串
string decodeString(const string& str, size_t& index) {
string res = "";
while (index < str.size() && str[index] != ')') {
if (isdigit(str[index])) {
int count = 0;
while (isdigit(str[index])) {
count = count * 10 + (str[index] - '0');
index++;
}
index++; // 跳过左括号
string subStr = decodeString(str, index);
index++; // 跳过右括号
while (count-- > 0) {
res += subStr;
}
} else {
res += str[index++];
}
}
return res;
}
int main() {
string str = "3(a2(b))c";
string encodedStr = encodeString(str);
cout << "Encoded string: " << encodedStr << endl; // 输出:3(97 2(98))99
size_t index = 0;
string decodedStr = decodeString(encodedStr, index);
cout << "Decoded string: " << decodedStr << endl; // 输出:aabbaabbcc
return 0;
}
```
阅读全文