How do I get up to the first n characters of a string in Java without doing a size check first (inline is acceptable) or risking an IndexOutOfBoundsException?
How do I get up to the first n characters of a string in
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s a neat solution:
Opinion: while this solution is "neat", I think it is actually less readable than a solution that uses
if/elsein 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 is more obvious in theif/elseversion. For a cleaner / more readable solution, see @paxdiablo’s answer.