How to get the first five character of a String

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

    You can use Enumerable.Take like:

    char[] array = yourStringVariable.Take(5).ToArray();
    

    Or you can use String.Substring.

    string str = yourStringVariable.Substring(0,5);
    

    Remember that String.Substring could throw an exception in case of string's length less than the characters required.

    If you want to get the result back in string then you can use:

    • Using String Constructor and LINQ's Take

      string firstFivChar = new string(yourStringVariable.Take(5).ToArray());
      

    The plus with the approach is not checking for length before hand.

    • The other way is to use String.Substring with error checking

    like:

    string firstFivCharWithSubString = 
        !String.IsNullOrWhiteSpace(yourStringVariable) && yourStringVariable.Length >= 5
        ? yourStringVariable.Substring(0, 5)
        : yourStringVariable;
    

提交回复
热议问题