How do I get rid of spaces(if any), in a String that I am manipualtng? For ex: String s = "some String"; Before I proceed to use this String, if I want to get rid of the space between 'some' and 'String', what's the easiest way of doing it? Thanks for your help.
Bosun Bello
Ranch Hand
Joined: Nov 06, 2000
Posts: 1506
posted
0
I am not sure if Java has a function that does that...At work, so I don't have my Java books handy. You can loop through the length of the string, using the charAt() method to see if it's spaces. And then move the characters you need into another variable. Good luck
Bosun (SCJP, SCWCD)
So much trouble in the world -- Bob Marley
Thanks Bodie! That's what I had in mind too, but wanted to know if there's a better way of doing this.
sunilchandwani
Greenhorn
Joined: Nov 28, 2000
Posts: 6
posted
0
How about this if you want to trim the string given on command line import java.io.*; class UseTrim{ public static void main(String args[])throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; do{ str = br.readLine(); str = str.trim(); System.out.println(str); }while(str == Null); } }
Ashutosh Uprety
Ranch Hand
Joined: Nov 30, 2000
Posts: 39
posted
0
Here is what I did ... The trim() method does away with trailing and leading spaces but not the in-between spaces. I think this is better than using IO
public class Test { public static void main(String args[]) { StringBuffer s1 = new StringBuffer("Hello u all"); StringBuffer s2 = new StringBuffer(); s2.ensureCapacity(s1.length()); for(int i=0;i<s1.length();i++) {> char c = s1.charAt(i); try { if(c != ' '){ s2.append(c); } }catch(StringIndexOutOfBoundsException e) { System.out.println(c); System.out.println("stringerror " + e); } } System.out.println(s1.toString()); System.out.println(s2.toString()); } }