string - How to implement trim() method in java by using only substring() method -
i know question quite silly, in interview told implement trim() method without using method string class except substring() method.
i approached problem using tochararray() , identifying first , last valid character of string. told not use tochararray() method.
could suggest approach it.
overriden methods of objects class allowed equals() , hashcode().
string untrimmed = " string "; string trimmed = ""; string innerspaces = ""; boolean wordboundary = true; try { (int = 0; ; i++) { string substr = untrimmed.substring(i, + 1); if (!substr.equals(" ") && !substr.equals("\t") && !substr.equals("\n") && !substr.equals("\r")) { trimmed += innerspaces + substr; wordboundary = false; innerspaces = ""; } else if (!wordboundary) { innerspaces += substr; } } } catch (indexoutofboundsexception e) { } system.out.println(trimmed);
Comments
Post a Comment