如何用给定的字符填充字符串,或者如果填充长度在C#中为0,如何将其置为空?
是否有一个函数几乎与String.PadLeft(int-length)的功能完全相同,只是如果长度为0,则将字符串设为空? 这就是我想做的:如何用给定的字符填充字符串,或者如果填充长度在C#中为0,如何将其置为空?,c#,padding,C#,Padding,是否有一个函数几乎与String.PadLeft(int-length)的功能完全相同,只是如果长度为0,则将字符串设为空? 这就是我想做的: string someText = "abc".PadLeft(8, '0'); Console.WriteLine(someText); string otherText = "xyz".PadLeft(0, '0'); Console.WriteLine(otherText); Console.WriteLine("Done!"); 我希望输出
string someText = "abc".PadLeft(8, '0');
Console.WriteLine(someText);
string otherText = "xyz".PadLeft(0, '0');
Console.WriteLine(otherText);
Console.WriteLine("Done!");
我希望输出如下:
00000abc
Done!
然而,实际输出如下:
00000abc
xyz
Done!
没有这样的方法。然而,你可以写你自己的,做你想要的 此方法的行为与经典的
PadLeft
完全相同,只是如果提供的长度为0,则返回空字符串
如果希望在填充长度小于字符串长度时返回空字符串,可以轻松地将条件从padLength==0
更改为padLength
public static class Extensions
{
public static string CustomPadLeft(this string input, int padLength, char padChar)
{
if (padLength == 0)
{
return string.Empty;
}
return input.PadLeft(padLength, padChar);
}
}
下面是验证行为的相应单元测试:
[TestMethod]
public void PadTest()
{
Assert.AreEqual(string.Empty, "xyz".CustomPadLeft(0, '0'));
Assert.AreEqual("xyz", "xyz".CustomPadLeft(2, '0'));
Assert.AreEqual("00000abc", "abc".CustomPadLeft(8, '0'));
}
我还建议您找到一个比我的
CustomPadLeft
更好的名字。没有这样的方法。然而,你可以写你自己的,做你想要的
此方法的行为与经典的PadLeft
完全相同,只是如果提供的长度为0,则返回空字符串
如果希望在填充长度小于字符串长度时返回空字符串,可以轻松地将条件从padLength==0
更改为padLength
public static class Extensions
{
public static string CustomPadLeft(this string input, int padLength, char padChar)
{
if (padLength == 0)
{
return string.Empty;
}
return input.PadLeft(padLength, padChar);
}
}
下面是验证行为的相应单元测试:
[TestMethod]
public void PadTest()
{
Assert.AreEqual(string.Empty, "xyz".CustomPadLeft(0, '0'));
Assert.AreEqual("xyz", "xyz".CustomPadLeft(2, '0'));
Assert.AreEqual("00000abc", "abc".CustomPadLeft(8, '0'));
}
我还建议您找到一个比我的
CustomPadLeft
…更好的名称,您希望“xyz”的结果是什么。PadLeft(2,'0');?编写一个扩展方法,其中,如果为0,则返回empty,否则返回padleft您可能必须编写扩展。padleft中的第一个参数是列宽,如果将列宽指定为0,则不会填充任何内容,因为填充仅在字符串长度小于列宽时发生。因此,您得到的是“xyz”作为输出。如果要返回空字符串,则应检查列宽是否为0,然后它应返回空。那么“xyz”的结果会是什么。PadLeft(2,'0');?编写一个扩展方法,其中,如果为0,则返回empty,否则返回padleft您可能必须编写扩展。padleft中的第一个参数是列宽,如果将列宽指定为0,则不会填充任何内容,因为填充仅在字符串长度小于列宽时发生。因此,您得到的是“xyz”作为输出。如果要返回空字符串,则应检查列宽是否为0,然后返回空字符串。