如何将字符插入字母数字字符串

Joh*_*ter 1 c# alphanumeric

我是C#的新手.我有一个简短的表单和一个长形式的客户端代码.短格式是一些字母字符和一些数字字符(ABC12),而长格式总是15个字符长,alpha和数字部分之间的空格用零填充(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"
}
Run Code Online (Sandbox Code Playgroud)

Emi*_*elt 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));
}
Run Code Online (Sandbox Code Playgroud)