净相当于旧VB的左侧(字符串,长度)的功能? [英] .Net equivalent of the old vb left(string, length) function?
问题描述
作为一个非.NET程序员,我正在寻找的.NET相当于旧的VB函数左(字符串,长度)
。这是懒惰的,因为它的工作任何长度的字符串。正如预期的那样,左(FOOBAR,3)=富
时,最有益,左(F,3)=F
。
As a non .net programmer I'm looking for the .net equivalent of the old vb function left(string, length)
. It was lazy in that it worked for any length string. As expected, left("foobar", 3) = "foo"
while, most helpfully, left("f", 3) = "f"
.
在.NET string.Substring(索引,长度)
引发的一切异常超出范围。在Java中,我总是有Apache的共享lang.StringUtils得心应手。在谷歌我没有得到很远的搜索字符串函数。
In .net string.Substring(index, length)
throws exceptions for everything out of range. In Java I always had the Apache-Commons lang.StringUtils handy. In Google I don't get very far searching for string functions.
编辑:
@Noldorin - 哇,谢谢你的vb.net扩展!我第一次遇到,但我花了几秒钟的时间在C#中做同样的:
@Noldorin - Wow, thank you for your vb.net extensions! My first encounter, although it took me several seconds to do the same in c#:
public static class Utils
{
public static string Left(this string str, int length)
{
return str.Substring(0, Math.Min(length, str.Length));
}
}
请注意静态的类和方法,以及在这
关键字。是的,他们是简单调用为foobar的。左(3)
。另请参见 C#扩展MSDN上。
Note the static class and method as well as the this
keyword. Yes, they are as simple to invoke as "foobar".Left(3)
. See also c# extensions on msdn.
推荐答案
下面是会做的工作的扩展方法。
Here's an extension method that will do the job.
<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 左
功能(即左(FOOBAR,3)
)或使用较新的VB.NET的语法,即
This means you can use it just like the old VB Left
function (i.e. Left("foobar", 3)
) or using the newer VB.NET syntax, i.e.
Dim foo = "f".Left(3) ' foo = "f"
Dim bar = "bar123".Left(3) ' bar = "bar"
这篇关于净相当于旧VB的左侧(字符串,长度)的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!