• Post Reply Bookmark Topic Watch Topic
  • New Topic

spaces in String  RSS feed

 
Asuthosh Borikar
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1512
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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());
}
}
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!