aspose file tools
The moose likes Beginning Java and the fly likes spaces in String Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "spaces in String " Watch "spaces in String " New topic
Author

spaces in String

Asuthosh Borikar
Ranch Hand

Joined: Sep 29, 2000
Posts: 75
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
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
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
How about this:
<PRE>
StringBuffer sb;
String s;
s = s.trim();
sb = new StringBuffer(s);
StringTokenizer st = new StringTokenizer(s);
while(st.hasMoreTokens()){
sb.append(st.nextToken());
}
s = sb.toString();
</PRE>
Asuthosh Borikar
Ranch Hand

Joined: Sep 29, 2000
Posts: 75
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
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
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());
}
}
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: spaces in String
 
Similar Threads
How to write back an updated record to db file?
Making spaces in between words
<ul><li> too much space after transformation
Perfect new line
AJAX request.responseXML is empty