How to get the first five character of a String

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

    You can use Substring(int startIndex, int length)

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

    The substring starts at a specified character position and has a specified length. This method does not modify the value of the current instance. Instead, it returns a new string with length characters starting from the startIndex position in the current string, MSDN

    What if the source string is less then five characters? You will get exception by using above method. We can put condition to check if the number of characters in string are more then 5 then get first five through Substring. Note I have assigned source string to firstFiveChar variable. The firstFiveChar not change if characters are less then 5, so else part is not required.

    string firstFiveChar = str;
    If(!String.IsNullOrWhiteSpace(yourStringVariable) && yourStringVariable.Length >= 5)
          firstFiveChar = yourStringVariable.Substring(0, 5);
    

提交回复
热议问题