How to trim StringBuffer object using substring method. - Java Language Basics

Java examples for Language Basics:StringBuffer

Description

How to trim StringBuffer object using substring method.

Demo Code


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

Result


Related Tutorials