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

后端 未结 11 1781
误落风尘
误落风尘 2020-12-02 17:50

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 lengt

相关标签:
11条回答
  • 2020-12-02 18:42

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

    0 讨论(0)
  • 2020-12-02 18:44

    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.

    0 讨论(0)
  • 2020-12-02 18:48

    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"
    
    0 讨论(0)
  • 2020-12-02 18:49

    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)
    
    0 讨论(0)
  • 2020-12-02 18:55

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

    0 讨论(0)
提交回复
热议问题