小编Mar*_* M.的帖子

regex/linq 用计数替换连续字符

我有以下方法(用 C#/.NET 编写)。输入文本仅包含字母(无数字)。返回值是另一种文本,其中包含两个以上连续字符的组被替换为前面带有重复计数的字符。例如:aAAbbcccc -> aAA3b4c

public static string Pack(string text)
{
    if (string.IsNullOrEmpty(text)) return text;

    StringBuilder sb = new StringBuilder(text.Length);

    char prevChar = text[0];
    int prevCharCount = 1;

    for (int i = 1; i < text.Length; i++)
    {
        char c = text[i];
        if (c == prevChar) prevCharCount++;
        else
        {
            if (prevCharCount > 2) sb.Append(prevCharCount);
            else if (prevCharCount == 2) sb.Append(prevChar);
            sb.Append(prevChar);

            prevChar = c;
            prevCharCount = 1;
        }
    }

    if (prevCharCount > 2) sb.Append(prevCharCount);
    else if (prevCharCount == 2) sb.Append(prevChar); …
Run Code Online (Sandbox Code Playgroud)

c# regex linq

2
推荐指数
1
解决办法
1484
查看次数

标签 统计

c# ×1

linq ×1

regex ×1