76

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Josh
  • 4,894
  • 6
  • 34
  • 42

11 Answers11

57

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"
Patrick J Collins
  • 959
  • 1
  • 14
  • 26
Noldorin
  • 144,213
  • 56
  • 264
  • 302
  • Was just typing up an example of an extension method. – j0tt May 09 '09 at 21:12
  • 1
    @Oded: They most certainly do in VB.NET 9. You need to specify the Extension attribute, which is quite different to the method for C#. See http://msdn.microsoft.com/en-us/library/bb384936.aspx – Noldorin May 09 '09 at 21:17
  • The original question stated nothing about an extension method. Seems to be going off on a tangent. – andleer May 09 '09 at 21:30
  • 5
    @Andrew Robinson: Not really, I think. Just because he didn't mention it, it doesn't mean it's not a valid (addition to the) answer. In fact, because he didn't refer to it, I suspected it was likely to be of *more* interest to him. Adding extra info that could be helpful never hurts. :) – Noldorin May 09 '09 at 21:40
37

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
35

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

Garry Shutler
  • 32,260
  • 12
  • 84
  • 119
17

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));
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CCondron
  • 1,926
  • 17
  • 27
7

Use:

using System;

public static class DataTypeExtensions
{
    #region Methods

    public static string Left(this string str, int length)
    {
        str = (str ?? string.Empty);
        return str.Substring(0, Math.Min(length, str.Length));
    }

    public static string Right(this string str, int length)
    {
        str = (str ?? string.Empty);
        return (str.Length >= length)
            ? str.Substring(str.Length - length, length)
            : str;
    }

    #endregion
}

It shouldn't error, returns nulls as empty string, and returns trimmed or base values. Use it like "testx".Left(4) or str.Right(12);

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jeff Crawford
  • 341
  • 4
  • 3
5

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
2

Another technique is to extend the string object by adding a Left() method.

Here is the source article on this technique:

http://msdn.microsoft.com/en-us/library/bb384936.aspx

Here is my implementation (in VB):

Module StringExtensions

    <Extension()>
    Public Function Left(ByVal aString As String, Length As Integer)
        Return aString.Substring(0, Math.Min(aString.Length, Length))
    End Function

End Module

Then put this at the top of any file in which you want to use the extension:

Imports MyProjectName.StringExtensions

Use it like this:

MyVar = MyString.Left(30)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brad Mathews
  • 1,567
  • 2
  • 23
  • 45
2

I like doing something like this:

string s = "hello how are you";
s = s.PadRight(30).Substring(0,30).Trim(); //"hello how are you"
s = s.PadRight(3).Substring(0,3).Trim(); //"hel"

Though, if you want trailing or beginning spaces then you are out of luck.

I really like the use of Math.Min, it seems to be a better solution.

danfolkes
  • 404
  • 4
  • 12
2

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!)

RobS
  • 3,807
  • 27
  • 34
  • You should not use Try...Catch to catch something that you can very easily check for beforehand. – Guffa May 09 '09 at 21:12
  • 1
    Why is using the VisualBasic namespace considered the "wrong way"? That's precisely why it is included. It's part of VB. – Chris Dunaway May 12 '09 at 14:40
0

Just in a very special case:

If you are doing this left and you will check the data with some partial string, for example:

if(Strings.Left(str, 1)=="*") ...;

Then you can also use C# instance methods, such as StartsWith and EndsWith to perform these tasks.

if(str.StartsWith("*"))...;

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hassan Faghihi
  • 1,888
  • 1
  • 37
  • 55
0

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
LarsTech
  • 80,625
  • 14
  • 153
  • 225
user3029478
  • 179
  • 1
  • 2