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

后端 未结 9 1874
挽巷
挽巷 2020-11-30 19:18

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 IndexOutOfBoundsExcept

相关标签:
9条回答
  • 2020-11-30 19:43
    String upToNCharacters = String.format("%."+ n +"s", str);
    

    Awful if n is a variable (so you must construct the format string), but pretty clear if a constant:

    String upToNCharacters = String.format("%.10s", str);
    

    docs

    0 讨论(0)
  • 2020-11-30 19:45

    Use the substring method, as follows:

    int n = 8;
    String s = "Hello, World!";
    System.out.println(s.substring(0,n);
    

    If n is greater than the length of the string, this will throw an exception, as one commenter has pointed out. one simple solution is to wrap all this in the condition if(s.length()<n) in your else clause, you can choose whether you just want to print/return the whole String or handle it another way.

    0 讨论(0)
  • 2020-11-30 19:48

    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 is more obvious in the if / else version. For a cleaner / more readable solution, see @paxdiablo's answer.

    0 讨论(0)
提交回复
热议问题