Package Stringtest;public class StringDemo4 {public static void main (string[] args) {String str = " abcdefg "; System.out.println ("original string:"); System.out.println ("str = (" + str + ")"); StringDemo4 sd4 = new StringDemo4 (); System.out.println ("String after removing space:"); Sd4.sop (Sd4.mytrim (str)); Str.trim ();} String Mytrim (String str) {int start = 0;int end = Str.length () -1;/*** Note: Start <= end and Str.charat (start) = = ' Two conditions are not in order to Exchange, * otherwise, when the entire character representable is a space, the start value will be equal to str.length (), greater than the maximum angle Mark Str.length () -1* condition Str.charat (start) = = " Causes a corner mark to be out of bounds exception stringindexoutofboundsexception,*&& is the execution of the first condition is false, the second condition will not execute */while (start <= End & & Str.charat (start) = = ") {start++;} While (end >= start && str.charat (end) = = ") {end--;} Return str.substring (Start, end+1); }//Print string void sop (String str) {System.out.println ("str = (" + str + ")");}
Trim method implementation in the string class of Java