CtrlAltDelete CtrlAltDelete - 1 year ago 76
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

in Java?

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

Answer Source

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();


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


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


return String.format("%." + Math.max(0, string.length() - 3) + "s", string);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download