当前位置 : 主页 > 网络编程 > net编程 >

c# 数字自增,返回指定长度字符串

来源:互联网 收集:自由互联 发布时间:2023-09-07
调用 #region 根据值生成指定长度的“字符串” { string val = "1"; int maxlength = 4; Console.WriteLine($"值:{val} 最大长度:{maxlength} 结果:{NumberAddSelf.GetNumberAddSelf(val, maxlength)}"); val = "11"; maxlengt

 调用

#region 根据值生成指定长度的“字符串”
{
string val = "1";
int maxlength = 4;
Console.WriteLine($"值:{val} 最大长度:{maxlength} 结果:{NumberAddSelf.GetNumberAddSelf(val, maxlength)}");

val = "11";
maxlength = 4;
Console.WriteLine($"值:{val} 最大长度:{maxlength} 结果:{NumberAddSelf.GetNumberAddSelf(val, maxlength)}");

val = "111";
maxlength = 4;
Console.WriteLine($"值:{val} 最大长度:{maxlength} 结果:{NumberAddSelf.GetNumberAddSelf(val, maxlength)}");

val = "1111";
maxlength = 4;
Console.WriteLine($"值:{val} 最大长度:{maxlength} 结果:{NumberAddSelf.GetNumberAddSelf(val, maxlength)}");

val = "1111";
maxlength = 6;
Console.WriteLine($"值:{val} 最大长度:{maxlength} 结果:{NumberAddSelf.GetNumberAddSelf(val, maxlength)}");
}
#endregion

结果

值:1 最大长度:4 结果:0002
值:11 最大长度:4 结果:0012
值:111 最大长度:4 结果:0112
值:1111 最大长度:4 结果:1112
值:1111 最大长度:6 结果:001112

核心方法

/// <summary>
/// 数字自增
/// </summary>
public class NumberAddSelf
{
/// <summary>
/// 数字自增,返回指定长度字符串
/// </summary>
/// <param name="valueString">值</param>
/// <param name="MaxLength">自增后,字符最大长度</param>
/// <returns></returns>
public static string GetNumberAddSelf(string NumberString, int MaxLength)
{
StringBuilder resultStringBuilder = new StringBuilder();
try
{
int NumberInt = Convert.ToInt32(NumberString.Trim());
NumberInt = NumberInt + 1;

int NumberIntLength = NumberInt.ToString().Length;

if (NumberIntLength == MaxLength)
{
resultStringBuilder.Append(NumberInt);
return resultStringBuilder.ToString();
}

if (NumberIntLength >= 1 && NumberIntLength < MaxLength)
{
//计算前面加多少个0
int res = (MaxLength - NumberIntLength);

for (int i = 0; i < res; i++)
{
resultStringBuilder.Append(0);
}

resultStringBuilder.Append(NumberInt);
}

}
catch (Exception e)
{
throw new Exception("转换int类型失败");
}

return resultStringBuilder.ToString().Trim();
}
}


网友评论