Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

c# - .NET equivalent of the old vb left(string, length) function

As a non-.NET programmer I'm looking for the .NET equivalent of the old Visual Basic 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".

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 - 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));
    }
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...