java - trim whitespace from a string? -



java - trim whitespace from a string? -

i writing function j2me application, don't have of more advanced / modern java classes available me. getting java.lang.arrayindexoutofboundsexception on this. so, apparently either doesn't way i've initialized newchars array, or i'm not doing correctly when calling system.arraycopy(). , advice appreciated!

/* * remove leading , trailing spaces */ public static string trim(string str) { char[] chars = str.tochararray(); int len = chars.length; // leading while ( (len > 0 ) && ( chars[0] == ' ' ) ) { char[] newchars = new char[] {}; // initialize empty array system.arraycopy(chars, 1, newchars, 0, len - 1); chars = newchars; len = chars.length; } // todo: trailing homecoming chars.tostring(); }

the simple way trim leading , trailing whitespace phone call string.trim(). if want trim leading , trailing spaces (rather leading , trailing whitespace), there apache commons method called stringutils.strip(string, string) can this; phone call " " 2nd argument.

your attempted code has number of bugs, , fundamentally inefficient. if want implement yourself, should:

count leading space characters count trailing space characters call string.substring(from, end) create new string containing characters want keep.

this approach avoids copying characters1.

1 - actually, depends on implementation of string. implementations there no copying, others single re-create made. either improvement on approach, entails minimum of 2 copies, , more if there characters trim.

java java-me

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -