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

2019-01-10 20:39发布

问题:

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".

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.

Edit:

@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.

回答1:

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"


回答2:

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



回答3:

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.



回答4:

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


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

edit: mine is in C#, you will have to change it for vb



回答6:

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
}

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



回答7:

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



回答8:

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)


回答9:

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.



回答10:

Just In Very Special Case:

If you are doing this left so then 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("*"))...;



回答11:

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


标签: c# .net vb.net