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

后端 未结 11 1780
误落风尘
误落风尘 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:28

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

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

    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.

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

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

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

    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("*"))...;

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

    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.

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