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

Viewed 80363

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.

11 Answers

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"

Another one line option would be something like the following:

myString.Substring(0, Math.Min(length, myString.Length))

Where myString is the string you are trying to work with.

Add a reference to the Microsoft.VisualBasic library and you can use the Strings.Left which is exactly the same method.

Don't forget the null case:

public static string Left(this string str, int count)
{
    if (string.IsNullOrEmpty(str) || count < 1)
        return string.Empty;
    else
        return str.Substring(0,Math.Min(count, str.Length));
}

You could make your own:

private string left(string inString, int inInt)
{
    if (inInt > inString.Length)
        inInt = inString.Length;
    return inString.Substring(0, inInt);
}

Mine is in C#, and you will have to change it for Visual Basic.

You can either wrap the call to substring in a new function that tests the length of it as suggested in other answers (the right way) or use the Microsoft.VisualBasic namespace and use left directly (generally considered the wrong way!)

If you want to avoid using an extension method and prevent an under-length error, try this

string partial_string = text.Substring(0, Math.Min(15, text.Length)) 
// example of 15 character max
Related