Hi, This code produce an array out of index error. Can any one help please?
HTML Code:/** * @(#)TrimEndSpaces.java * Program to trim any space at the end of a string * * @author Marshall * @version 1.00 2010/3/10 */ public class TrimEndSpaces { static String trim(String s) { char chr[] = s.toCharArray(); int i=0; int length = chr.length; while(chr[length]==' ') { length--; } char trimmed[] = new char[length]; //Define and Store the new trimmed string in char array for(i=0;i<length;i++) { trimmed[i]=chr[i]; } String trimmedString = new String (trimmed); // Converts the trimmed char array to string. return trimmedString; } public static void main(String args[]) { String str = "Do "; str = trim(str); System.out.println(str); } }
Same thing as in your previous post. When you convert a string to an array, the last element in array is not at index str.length()!!!!!!! It's at index (str.length()-1). Array indexes vary from 0 to (#array elements -1).
try
instead.Code:while(chr[length-1]==' ')
Btw, why do you reinvent this method anyway? there's method trim() in the String class...
Hi,
Must say thanks to you before I go back and correct the code. I was asked by my trainer to make own function for that.
thanks again
Now it works like magic!
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks