作为一名非.NET程序员,我正在寻找旧的Visual Basic function left(string, length)
的.NET等效项。它是懒惰的,因为它对任何长度的字符串都有效。正如预期的那样,left("foobar", 3) = "foo"
,而最有用的是,left("f", 3) = "f"
。
在.NET中,string.Substring(index, length)
会对超出范围的所有内容抛出异常。在Java中,我总是手头上有Apache-Commons lang.StringUtils。在Google中,我对字符串函数的搜索并不是很深入。
@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。
发布于 2009-05-09 21:10:12
下面是一个可以完成这项工作的扩展方法。
<System.Runtime.CompilerServices.Extension()> _
Public Function Left(ByVal str As String, ByVal length As Integer) As String
Return str.Substring(0, Math.Min(str.Length, length))
End Function
这意味着您可以像使用旧的VB Left
函数(即Left("foobar", 3)
)一样使用它,也可以使用较新的VB.NET语法。
Dim foo = "f".Left(3) ' foo = "f"
Dim bar = "bar123".Left(3) ' bar = "bar"
发布于 2009-05-09 21:11:30
另一行选项将类似于以下内容:
myString.Substring(0, Math.Min(length, myString.Length))
其中,myString是您尝试使用的字符串。
发布于 2009-05-09 21:19:14
添加对Microsoft.VisualBasic库的引用,您就可以使用Strings.Left,这是完全相同的方法。
https://stackoverflow.com/questions/844059
复制相似问题