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#?
string str = "GoodMorning"
string strModified = str.Substring(0,5);
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.