CtrlAltDelete CtrlAltDelete - 2 months ago 8
Java Question

Removing last three characters of a String w/o using Substring

Is there anyway to remove the last three characters of a string without using

Substring();
in Java?

String stringOfFileName = this.first.imageHelper() + this.rest.images();
return stringOfFileName - *last three characters*;

Answer

It's a pretty weird restriction, but you can do it like this:

StringBuilder sb = new StringBuilder(string);
sb.setLength(Math.max(0, string.length() - 3));
return sb.toString();

or

char[] cs = string.toCharArray();
return new String(cs, 0, Math.max(0, cs.length - 3));

or

return string.replaceFirst(".{0,3}$", "");

or

return String.format("%." + Math.max(0, string.length() - 3) + "s", string);