How to get the first five character of a String

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 … Read more

How do I get the first n characters of a string without checking the size or going out of bounds?

Here’s a neat solution: String upToNCharacters = s.substring(0, Math.min(s.length(), n)); Opinion: while this solution is “neat”, I think it is actually less readable than a solution that uses if / else in the obvious way. If the reader hasn’t seen this trick, he/she has to think harder to understand the code. IMO, the code’s meaning … Read more