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

后端 未结 9 1918
挽巷
挽巷 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

提交回复
热议问题