用整数替换###

时间:2016-11-08 17:34:55

标签: c#

通过使用RegEx或String.Replace,我需要用整数替换任意数量的连续#(具有相应数量的前导0' s)。我知道我可以在字符串中搜索#,获取First和Last索引,Last-First作为长度,然后用String.Replace替换。我希望有人会有更快,更光滑的答案。

方法标题是:

string ReplaceHashtagsWithInt(string input, int integer)

示例:

输入 - > "字符串#### _嗨##",2

输出 - > " String0002_Hi02"

输入 - > "字符串#### _嗨##",123

输出 - > " String0123_Hi123"

2 个答案:

答案 0 :(得分:3)

public static class Testing
{
    public static void Main()
    {
        ReplaceHashtagsWithInt("String####_Hi##", 2);
        ReplaceHashtagsWithInt("String####_Hi###", 123);
        ReplaceHashtagsWithInt("String####_Hi#######", 123);
    }

    public static string ReplaceHashtagsWithInt(string input, int integer)
    {
        Regex regex = new Regex("#+");

        var matches = regex.Matches(input).Cast<Match>().Select(m => m.Value).ToArray();
        Array.Sort(matches);
        Array.Reverse(matches);

        foreach (string match in matches)
        {
            Regex r = new Regex(match);
            string zeroes = new string('0', match.Length - integer.ToString().Length) + integer;
            input = r.Replace(input, zeroes);
        }

        return input;
    }
}

答案 1 :(得分:1)

您可以这样做:

using System;
using System.Text;
using System.Text.RegularExpressions;

public static class Testing
{
    public static void Main()
    {
        Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 1));
        Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 23));
        Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 456));
        Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 7890));
        Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 78901));
    }

    public static string ReplaceHashtagsWithInt(string input, int integer)
    {
        Regex regex = new Regex("#+");

        StringBuilder output = new StringBuilder(input);
        int allig = 0;      

        for(Match match = regex.Match(input);match.Success;match = match.NextMatch())        
        {

            string num = integer.ToString();

            if(num.Length<=match.Length)
                for(int i=0;i<match.Length;i++)
                {
                    if(i<match.Length-num.Length)
                        output[match.Index+i+allig] = '0';
                    else
                        output[match.Index+i+allig] = num[i-match.Length+num.Length];
                }
            else
            {
                output.Remove(match.Index+allig,match.Length);
                output.Insert(match.Index+allig,num);
                allig+=num.Length-match.Length;
            }
        }

        return output.ToString();
    }
}