Java examples for Language Basics:StringBuffer
How to trim StringBuffer object using substring method.
public class Main { // w w w . j a v a2s.co m public static void main(String[] args) { StringBuffer sbf = new StringBuffer(" Hello World ! "); String str = sbf.toString().trim(); System.out.println("StringBuffer trim: \"" + str +"\""); System.out.println("\"" + trim(sbf) + "\""); } private static String trim(StringBuffer sbf){ int start, end; for(start = 0; start < sbf.length(); start++){ if(sbf.charAt(start) != ' ') break; } //find the last character which is not space for(end = sbf.length(); end > start ; end--){ if(sbf.charAt(end-1) != ' ') break; } return sbf.substring(start, end); } }