C# WinForm 字符串压缩:简单实现及代码示例

本文提供了一个简单的 C# WinForm 程序示例,演示如何使用两个文本框实现字符串压缩功能。示例代码仅处理字母字符,并解释了压缩算法的逻辑。

界面设计:

在窗体设计器中,添加以下控件:

  • 两个文本框,分别命名为 'inputTextBox' 和 'outputTextBox'。
  • 一个按钮,命名为 'compressButton'。

代码实现:

using System;
using System.Linq;
using System.Windows.Forms;

namespace StringCompression
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void compressButton_Click(object sender, EventArgs e)
        {
            string input = inputTextBox.Text;

            if (string.IsNullOrEmpty(input))
            {
                MessageBox.Show('Please enter a string to compress.', 'Error');
                return;
            }

            string compressed = CompressString(input);

            outputTextBox.Text = compressed;
        }

        private string CompressString(string input)
        {
            char[] chars = input.ToCharArray();

            string compressed = '';

            for (int i = 0; i < chars.Length; i++)
            {
                int count = 1;

                while (i < chars.Length - 1 && chars[i] == chars[i + 1])
                {
                    count++;
                    i++;
                }

                compressed += chars[i] + count.ToString();
            }

            return compressed;
        }
    }
}

功能说明:

  1. 获取输入字符串: 在 'compressButton_Click' 方法中,获取 'inputTextBox' 中的输入字符串。
  2. 检查输入: 判断输入字符串是否为空,若为空则显示错误消息并退出。
  3. 压缩字符串: 调用 'CompressString' 方法对输入字符串进行压缩。
  4. 显示压缩结果: 将压缩后的结果显示在 'outputTextBox' 中。

压缩算法:

'CompressString' 方法使用循环遍历字符数组。对于每个字符,记录其连续出现的次数,并将字符和次数拼接成压缩后的字符串。例如:

  • 输入字符串:'AAAABBBCCDAA'
  • 压缩结果:'A4B3C2DA2'

注意:

  • 该示例仅处理字母字符,若输入包含数字或特殊字符,可能导致错误。
  • 实际应用中需要根据具体需求进行修改和扩展。
C# WinForm 字符串压缩:简单实现及代码示例

原文地址: https://www.cveoy.top/t/topic/lq19 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录