c# - char 二维数组压缩
问题描述
有一个 .txt 文件,我必须阅读、压缩并为压缩的 txt制作输出txt。谁能告诉我应该在我的代码中修复什么?
我的代码:
namespace Tomorites
{
class Compression
{
public void Compress(char[,] source)
{
for (int i = 0; i < source.GetLength(0); i++)
{
int white = 0;
int red = 0;
for (int j = 0; j < source.GetLength(1); j++)
{
if (source[i, j] == 'P')
{
if (source[i, j] > 0)
{
red++;
Console.Write(red + " P ");
}
}
else if(source[i,j]=='F')
{
if (source[i, j] > 0)
{
white++;
Console.Write(white + " F ");
}
}
}
Console.WriteLine();
}
}
}
}
解决方案
你可以尝试这样的事情(你可以摆弄代码):
public static string Compress(char[,] source) {
if (null == source || source.GetLength(0) <= 0 || source.GetLength(1) <= 0)
return "";
StringBuilder sb = new StringBuilder();
for (int row = 0; row < source.GetLength(0); ++row) {
if (sb.Length > 0)
sb.AppendLine();
int count = 0;
char prior = '\0';
bool left = true;
for (int col = 0; col < source.GetLength(1); ++col) {
if (count == 0 || prior == source[row, col])
count += 1;
else {
if (!left)
sb.Append(' ');
left = false;
sb.Append($"{count} {prior}");
count = 1;
}
prior = source[row, col];
}
if (!left)
sb.Append(' ');
sb.Append($"{count} {prior}");
}
return sb.ToString();
}
演示:
char[,] test = new char[,] {
{'a', 'a', 'a', 'a'},
{'a', 'b', 'c', 'c'},
};
Console.WriteLine(Compress(test));
结果:
4 a
1 a 1 b 2 c
推荐阅读
- c++ - 结构字段名称与 GDB 中的 stl 数组冲突
- kubernetes - 运行 Kompose 后,我得到: pod has unbound immediate PersistentVolumeClaims
- ruby-on-rails - Template::Error undefined method `[]' for nil:NilClass
- reactjs - 未应用 React JS Bootstrap
- javascript - 在 Node Express App 的不同 js 文件中使用环境变量
- amazon-web-services - 谁能帮我理解aws中的Route 53
- javascript - 如何在 twig 中获取当前的锚点/_fragment
- haskell - 使用 cabal new-install 重新安装相同版本的软件包
- android - Android UI 测试:为什么没有调用 LiveData 的观察者?
- javascript - 如何创建适用于移动设备的 youtube 自动订阅链接?