How to get the first five character of a String

后端 未结 20 2245
醉酒成梦
醉酒成梦 2020-12-01 05:01

I have read this question to get first char of the string. Is there a way to get the first n number of characters from a string in C#?

相关标签:
20条回答
  • 2020-12-01 05:24

    I use:

    var firstFive = stringValue?.Substring(0, stringValue.Length >= 5 ? 5 : customAlias.Length);
    

    or alternative if you want to check for Whitespace too (instead of only Null):

    var firstFive = !String.IsNullOrWhiteSpace(stringValue) && stringValue.Length >= 5 ? stringValue.Substring(0, 5) : stringValue
    
    0 讨论(0)
  • 2020-12-01 05:27

    If we want only first 5 characters from any field, then this can be achieved by Left Attribute

    Vessel = f.Vessel !=null ? f.Vessel.Left(5) : ""
    
    0 讨论(0)
  • 2020-12-01 05:31

    Use the PadRight function to prevent the string from being too short, grab what you need then trim the spaces from the end all in one statement.

    strSomeString = strSomeString.PadRight(50).Substring(0,50).TrimEnd();
    
    0 讨论(0)
  • 2020-12-01 05:31

    This is how you do it in 2020:

    var s = "ABCDEFGH";
    var first5 = s.AsSpan(0, 5);
    

    A Span<T> points directly to the memory of the string, avoiding allocating a temporary string. Of course, any subsequent method asking for a string requires a conversion:

    Console.WriteLine(first5.ToString());
    

    Though, these days many .NET APIs allow for spans. Stick to them if possible!

    Note: If targeting .NET Framework add a reference to the System.Memory package, but don't expect the same superb performance.

    0 讨论(0)
  • 2020-12-01 05:32

    Kindly try this code when str is less than 5.

    string strModified = str.Substring(0,str.Length>5?5:str.Length);
    
    0 讨论(0)
  • 2020-12-01 05:33

    Just a heads up there is a new way to do this in C# 8.0: Range operators

    Microsoft Docs

    Or as I like to call em, Pandas slices.

    Old way:

    string newString = oldstring.Substring(0, 5);
    

    New way:

    string newString = oldstring[..5];
    

    Which at first glance appears like a pretty bad tradeoff of some readability for shorter code but the new feature gives you

    1. a standard syntax for slicing arrays (and therefore strings)
    2. cool stuff like this:

      var slice1 = list[2..^3]; // list[Range.Create(2, Index.CreateFromEnd(3))]

      var slice2 = list[..^3]; // list[Range.ToEnd(Index.CreateFromEnd(3))]

      var slice3 = list[2..]; // list[Range.FromStart(2)]

      var slice4 = list[..]; // list[Range.All]

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