作为一名非 .NET 程序员,我正在寻找与旧的 Visual Basic 函数 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 .
最佳答案
这是一个可以完成这项工作的扩展方法。
<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"
关于c# - .NET 相当于旧的 vb left(string, length) 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/844059/