How to get the first five character of a String

后端 未结 20 2366
醉酒成梦
醉酒成梦 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:31

    This is how you do it in 2020:

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

    A Span 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.

提交回复
热议问题