用整数替换###

本文关键字:替换 整数 | 更新日期: 2023-09-27 18:16:55

通过使用RegEx或String。替换,我需要用一个整数替换任意数量的连续#(与适当数量的前导0)。我知道我可以在字符串中搜索#,获得First和Last索引,Last-First的长度,然后替换为string . replace。我希望有人能有一个更快、更圆滑的答案。

方法头应该是:

string ReplaceHashtagsWithInt(string input, int integer)

例子:

Input -> "String####_Hi##", 2

输出-> "String0002_Hi02"

Input -> "String####_Hi##", 123

输出-> "String0123_Hi123"

用整数替换###

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;
    }
}

你可以这样做:

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();
    }
}