模式子串C# [英] Pattern substring C#

查看:89
本文介绍了模式子串C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个字符串模式...

我使用PadRight但不适合我。你能帮助我吗 ?



如果我把1放在textBox1上我的结果:\ LOT_0001

如果我把11放在textBox1上我的结果:\ LOT_00011 - < ;这个错了。我想要:\ LOT_0011





I need a pattern for strings...
I used PadRight but not work well for me. Can you help-me ?

if I put 1 on textBox1 My result: \LOT_0001
if I put 11 on textBox1 My result: \LOT_00011 -< this wrong. I want: \LOT_0011


public static class PatternFileAndFolder
{
    private static string _lote = @"\LOT_";
    private static string _documento = @"\DOC_";

    public static string LotePattern
    {
        get{return _lote.PadRight(8, '0') ;}
    }

    public static string DocumentoPattern
    {
        get { return _documento.PadRight(8, '0'); }
    }
}




textBox2.Text = PatternFileAndFolder.LotePattern + textBox1.Text;

推荐答案

如下所示:



How about something like:

string _lote = @"\LOT_{0:0000}";
string x = System.String.Format ( _lote , 11 ) ;


试试这个:

Try this:
private static string _lote = @"\LOT_00";

private static string LotePattern(string stringToPad)
{
    return _lote + ((stringToPad.Length == 1) ? "0" : "") + stringToPad;
}

测试:

string test1 = "1";
string test2 = "11";

string result1 = LotePattern(test1);
string result2 = LotePattern(test2);


尝试以下方法





Try the below method


private string AddLeadingZeros(int totalLength, string originalNumber)
        {
            string leadingZeros = string.Empty;
            int counter = 0;
            try
            {
                counter = totalLength - originalNumber.Length;
                for (int leadingZeroCount = 0; leadingZeroCount < counter; leadingZeroCount++)
                {
                    leadingZeros += "0";
                }
                originalNumber = leadingZeros + originalNumber;
            }
            catch (Exception ex)
            { LogExceptionDetails(ex); }
            return originalNumber;
        }









在您需要的方法中传递两个参数,第一个是总长度,第二个是数字。根据长度的不同,它将计算要添加到字符串中的零的数量。



例如,让我们考虑总长度为4并且您传递的原始字符串是1。现在计算总长度的差异 - 原始字符串的长度(4 - 1)然后它将向原始字符串添加三个零。如果您将原始值视为01,它将添加两个零,依此类推。





In the method you will need to pass two parameters the first one is the total length and the second one is the number. Basing on the difference of lengths it will calculate the number of zero's to be added to the string.

For example let us consider that the total length is "4" and the original string which you are passing is "1". Now calculate the difference that is total length - length of the original string (4 - 1) then it will add three zero's to the original string. If you consider your original value as "01" the it will add two zero's and so on.


这篇关于模式子串C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆