1

我是 C# 的新手。我有一个短格式和一个长格式的客户端代码。短格式是一些字母字符和一些数字字符 (ABC12),而长格式总是 15 个字符长,字母和数字部分之间的空格用零填充 (ABC000000000012)。我需要能够从短格式转换为长格式。下面的代码是我如何让它工作的——这是最好的方法吗?

public string ExpandCode(string s)
{
    // s = "ABC12"
    int i = 0;
    char c;
    bool foundDigit = false;
    string o = null;

    while (foundDigit == false)
    {
        c = Convert.ToChar(s.Substring(i, 1));
        if (Char.IsDigit(c))  
        {
            foundDigit = true;
            o = s.Substring(0, i) + new String('0', 15-s.Length) + s.Substring(i,s.Length-i); 
        }
        i += 1;
    }
    return (o); //o = "ABC000000000012"
}
4

4 回答 4

5

您的代码基本上是正确的,但是它可能会很慢,因为String.Substring(...)每次调用都会创建一个新字符串。

我还建议您使用 .NET api 的内置函数来完成您的任务,这可以使编码更容易:

private char[] numbers = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};

public string ExpandCode(string s)
{
    //Find the first numeric char.
    int index = s.IndexOfAny(numbers);
    //Insert zeros and return the result. 
    return s.Insert(index, new String('0', 15 - s.Length));
}
于 2013-11-12T12:53:12.267 回答
1

看看这个:

public string ExpandCode(string s)
{
    var builder = new StringBuilder(s);
    var index = Array.FindIndex(s.ToArray(), x => char.IsDigit(x));

    while (builder.Length < 15)
    {
        builder.Insert(index, '0');
    }

    return builder.ToString();
}

我假设字符串总是字母 -> 数字(如“abc123”或“ab1234”)。

于 2013-11-12T13:01:29.467 回答
1

越纯越快

public static string ExpandCode4(string s)
{
    char[] res = new char[15];
    int ind = 0;
    for (int i = 0; i < s.Length && s[i] >= 'A'; i++)
        res[ind++] = s[i];
    int tillDigit = ind;
    for (int i = 0; i < 15 - s.Length; i++)
        res[ind++] = '0';
    for (int i = 0; i < s.Length - tillDigit; i++)
        res[ind++] = s[tillDigit + i];
    return new string(res);
}

所有答案的基准如下,

internal class Program
{
    private static void Main(string[] args)
    {
        var inputs = new List<string>();
        for (int i = 0; i < 10000000; i++)
        {
            inputs.Add("ABC1234");
        }

        var n1 = DateTime.Now;
        inputs.ForEach(i => ExpandCode1(i));
        var r1 = (DateTime.Now - n1).Ticks;

        var n2 = DateTime.Now;
        inputs.ForEach(i => ExpandCode2(i));
        var r2 = (DateTime.Now - n2).Ticks;

        var n3 = DateTime.Now;
        inputs.ForEach(i => ExpandCode3(i));
        var r3 = (DateTime.Now - n3).Ticks;

        var n4 = DateTime.Now;
        inputs.ForEach(i => ExpandCode4(i));
        var r4 = (DateTime.Now - n4).Ticks;

        var results = new List<Result>()
        {
            new Result() {Name = "1", Ticks = r1},
            new Result() {Name = "2", Ticks = r2},
            new Result() {Name = "3", Ticks = r3},
            new Result() {Name = "4", Ticks = r4}
        };
        results.OrderBy(r => r.Ticks).ToList().ForEach(Console.WriteLine);
        Console.ReadKey();
    }

    public static string ExpandCode4(string s)
    {
        char[] res = new char[15];
        int ind = 0;
        for (int i = 0; i < s.Length && s[i] >= 'A'; i++)
            res[ind++] = s[i];
        int tillDigit = ind;
        for (int i = 0; i < 15 - s.Length; i++)
            res[ind++] = '0';
        for (int i = 0; i < s.Length - tillDigit; i++)
            res[ind++] = s[tillDigit + i];
        return new string(res);
    }
    public static string ExpandCode1(string s)
    {
        char[] numbers = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
        //Find the first numeric char.
        int index = s.IndexOfAny(numbers);
        //Insert zeros and return the result. 
        return s.Insert(index, new String('0', 15 - s.Length));
    }

    public static string ExpandCode2(string s)
    {
        var builder = new StringBuilder(s);
        var index = Array.FindIndex(s.ToArray(), x => char.IsDigit(x));

        while (builder.Length < 15)
        {
            builder.Insert(index, '0');
        }

        return builder.ToString();
    }

    public static string ExpandCode3(string s)
    {
        var match = Regex.Match(s, @"([^\d]+)(\d+)");
        var letters = match.Groups[1].Value;
        var numbers = int.Parse(match.Groups[2].Value);
        var formatString = "{0}{1:d" + (15 - letters.Length) + "}";
        var longForm = string.Format(formatString, letters, numbers);
        return longForm;
    }

}
public class Result
{
    public long Ticks { get; set; }
    public string Name { get; set; }
    public override string ToString()
    {
        return Name + " - " + Ticks;
    }
}
于 2013-11-12T13:32:09.293 回答
0

您可以使用 string.Format() 为您处理填充。我使用正则表达式(并且不是以一种非常健壮的方式)来解析字母和数字,但您可以通过另一种方式更有效地做到这一点。

关键是我们动态地计算出我们需要多少个零,然后使用格式字符串,X:dY其中 X = 格式序数和 Y = 您希望填充的零的数量。

var match = Regex.Match("ABC12", @"([^\d]+)(\d+)");
var letters = match.Groups[1].Value;
var numbers = int.Parse(match.Groups[2].Value);
var formatString = "{0}{1:d" + (15 - letters.Length) + "}";
var longForm = string.Format(formatString, letters, numbers);
于 2013-11-12T12:57:54.897 回答