Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override toString to remove spaces between elements

As you know, the toString() method called on a Vector output this

[foo, bar, item, item4]

This is pretty basic but, how could I get this instead (removing white spaces between elements)?

[foo,bar,item,item4]

Thank you all

EDIT: return nom.toString().replace(" ", ""); is not a solution !

like image 915
user1023021 Avatar asked Nov 01 '11 18:11

user1023021


People also ask

How do I remove extra spaces from a string?

Use replace () function to replace all the space characters with a blank. The resulting string will not have any spaces in-between them.

What happen when you override a toString () method?

By overriding the toString( ) method, we are customizing the string representation of the object rather than just printing the default implementation. We can get our desired output depending on the implementation, and the object values can be returned.

How do I remove extra spaces between strings in Java?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

Why we do override toString ()?

When you print an object, by default the Java compiler invokes the toString() method on the object. So by overriding the toString() method, we can provide meaningful output.


2 Answers

Wrap your vector class and override toString.

import java.util.*;
class AwesomeVector<E> extends Vector<E> {

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for(int i = 0; i < size(); i++) {
           if(i != 0) sb.append(","); 
           sb.append(get(i));
        }
        sb.append("]");
        return sb.toString();
    }

    public static void main(String[] args) {
        AwesomeVector<String> av = new AwesomeVector<String>();
        av.add("This");
        av.add("is");
        av.add("a test");
        System.out.println(av.toString());
    }

}


C:\Documents and Settings\glowcoder\My Documents>javac AwesomeVector.java

C:\Documents and Settings\glowcoder\My Documents>java AwesomeVector
[This,is,a test]
like image 97
corsiKa Avatar answered Oct 29 '22 13:10

corsiKa


Overriding only makes sense if you are subclassing Vector.

If you are, then you can use Apache Commons Lang's StringUtils.join as follows:

@Override
public String toString() {
    return "[" + StringUtils.join(this, ",") + "]";
}

If you want to stay in plain Java, glowcoder has the best answer.

like image 39
Ray Toal Avatar answered Oct 29 '22 13:10

Ray Toal