酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

C++实现 decode 函数:解压缩 “a2b10cd2” 字符串

```cpp #include <iostream> #include <string> #include <cctype> std::string decode(const std::string& input) { std::string result; size_t i = 0; while (i < input.size()) { char currentChar = input[i]; i++; int count = 0; while (i < input.size() && std::isdigit(input[i])) { count = count * 10 + (input[i] - '0'); i++; } for (int j = 0; j < count; ++j) { result += currentChar; } } return result; } int main() { std::string input = "a2b10cd2"; std::string output = decode(input); std::cout << "Decoded string: " << output << std::endl; // Output should be "aabbbbbbbbbbcdcd" return 0; } ``` 解释: 1. 函数定义:`std::string decode(const std::string& input)`,该函数接受一个字符串并返回解压缩后的字符串。 2. 变量初始化:`result`用于存储最终的解压结果,`i`用于遍历输入字符串。 3. 循环处理:使用`while`循环遍历输入字符串,每次读取一个字符和其后的数字。 4. 数字解析:通过嵌套的`while`循环解析连续的数字,将其转换为整数`count`。 5. 字符重复:根据解析出的数字`count`,将当前字符添加到结果字符串中。 6. 主函数测试:在`main`函数中调用`decode`函数并输出结果以验证正确性。 ######[AI写代码神器 | 425点数解答 | 2025-02-02 23:37:24]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]