以C++为单位进行运行长度编码
Run length encoding in C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string compression(const string & str){
int i = str.size();
string letters;
letters[0] = str[0];
for (int j = 0; j < i; ++j){
int count = 1;
while (str[j] == str[j+1]){
count++;
j++;
}
letters.push_back('0' + count);
letters.push_back(str[j]);
}
return letters;
}
int main(){
string input;
char c;
try {
cout << "Enter the data to be compressesed: "<< endl;
cin >> input;
for (int z = 0; z < input.length(); ++z){
c = input.at(z);
}
if (!(c >= 'a' && c <= 'z')){
throw runtime_error("error: invalid input");
}
}
catch (runtime_error& excpt){
cout << excpt.what() <<endl;
return 0;
}
cout << "The compressed data is " << compression(input) << endl;
return 0;
}
预期的输出是 ,对每组字符重复执行。这是按顺序重复的次数。
一些例子:
aaeeeeae = 2a4e1a1e
rr44errre = 无效输入
eeee = 21e
仅当字符连续重复 9 次或更少时,代码才能正常工作。 对于 10 或更大的值,输入是其他符号。 例如,它在 10 中保持空白,因此如果输入是"aaaabb",则输出只是"a2b"而不是"10a2b"。对于 11 个输出 ';', 因此,如果输入是"aaa出于某种原因,A2B'。
所以我的问题是,我如何使反推适用于所有数字,而不仅仅是从 0 到 9?
如果你来到这里,谢谢你的时间。^^
如果你可以使用 c++11 或更高版本,你的函数compression
可能看起来像:
string compression(const string & str){
int i = str.size();
string letters;
for (int j = 0; j < i; ++j){
int count = 1;
while (str[j] == str[j+1]){
count++;
j++;
}
letters += std::to_string(count);
letters.push_back(str[j]);
}
return letters;
}
相关文章:
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何确定我已使用非编码文件到达 EOF?
- 代码在main()中运行,但在函数中出现错误
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何在运行中期切换GTK CSS style_context
- 如何在MS Visual Studio 2019中运行QT UI
- 运行长度编码程序 c++ 的问题
- 以C++为单位进行运行长度编码
- 如何制作硬编码堆栈,而不是硬编码并保持程序正常运行
- Targa 运行长度编码
- 运行长度编码算法[数据压缩].
- 嗨,我正在尝试编码一个允许用户在Visual C 中登录的按钮,程序正在运行,但表单对话框未显示
- 无论如何,我可以在visualstudio2005上与visualstudio2015一起运行一个已经编码的项目吗
- 如何检查在运行程序的控制台上设置了哪些字符编码
- 如何使用 Java 在用 C++ 和 Direct9 编码的网页中运行应用程序
- 运行长度编码(整数)