How to get the first five character of a String

后端 未结 20 2246
醉酒成梦
醉酒成梦 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:41
    string str = "GoodMorning"
    
    string strModified = str.Substring(0,5);
    
    0 讨论(0)
  • 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.

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