No loop is required since a string can be split into an array in one call to String.split . (Note that String.split accepts a regular expression.) To handle the "level", simply subtract it from the length of the section array. Instead of copying the array subrange, convert it to a list and use subList ():
String getResponse(String str, int level) { String[] splits = str.split("\\."); if (level < 0 || level > splits.length) { throw new IllegalArgumentException(); } return String.join(".", Arrays.asList(splits).subList(0, splits.length - level)); }
Conclusion
for (int level = 0; level < 5; level++) { System.out.printf("level %d: %s%n", level, getResponse("ABCD", level)); }
will be
level 0: ABCD level 1: ABC level 2: AB level 3: A level 4:
Please note that this requires Java 8, because it requires String.join() . (But it does not require threads or even lambda!)
source share