How to get the first five character of a String

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

    The problem with .Substring(,) is, that you need to be sure that the given string has at least the length of the asked number of characters, otherwise an ArgumentOutOfRangeException will be thrown.

    Solution 1 (using 'Substring'):

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

    The drawback of using .Substring( is that you'll need to check the length of the given string.

    Solution 2 (using 'Take'):

    var firstFive = stringValue != null ? 
                        string.Join("", stringValue.Take(5)) : 
                        null;
    

    Using 'Take' will prevent that you need to check the length of the given string.

提交回复
热议问题