How to get the first five character of a String

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

    No one mentioned how to make proper checks when using Substring(), so I wanted to contribute about that.

    If you don't want to use Linq and go with Substring(), you have to make sure that your string is bigger than the second parameter (length) of Substring() function.

    Let's say you need the first 5 characters. You should get them with proper check, like this:

    string title = "love" // 15 characters
    var firstFiveChars = title.Length <= 5 ? title : title.Substring(0, 5);
    
    // firstFiveChars: "love" (4 characters)
    

    Without this check, Substring() function would throw an exception because it'd iterate through letters that aren't there.

    I think you get the idea...

提交回复
热议问题