作为一个非政府组织.NET程序员我正在寻找.NET相当于旧的Visual Basic函数left(string, length)
.它是懒惰的,因为它适用于任何长度的字符串.正如所料,left("foobar", 3) = "foo"
人,而最有帮助的是left("f", 3) = "f"
人.
在里面NET string.Substring(index, length)
对超出范围的所有内容抛出异常.在Java中,我总是随身携带Apache Commons lang.StringUtils.在谷歌,我搜索字符串函数的时间不长.
@Noldorin-哇,谢谢你的VB.NET扩展!我的第一次遇到,尽管我花了几秒钟才用C#做了同样的事情:
public static class Utils
{
public static string Left(this string str, int length)
{
return str.Substring(0, Math.Min(length, str.Length));
}
}
请注意静电的类和方法以及关键字this
.是的,调用它们就像调用"foobar".Left(3)
一样简单.另请参见C# extensions on MSDN.