user3413170
user3413170

Reputation: 261

How to return string without excess

I have this toString method for a linked list and it prints it out in an array like fashion, but it also prints out excess characters. How do I get rid of the last ", "?

public String toString() {
  String ret = "[";
  Node current = head;
  while(current.getNext() != null) {
    current = current.getNext();
    ret += current.get() + ", ";
  }
  return ret + "]";
}

Example: we have a linked list with 3 elements, and then we print it out.

"[1, 2, 3, ]"

Upvotes: 0

Views: 125

Answers (7)

Wendel
Wendel

Reputation: 2977

I use Apache Commons Lang - StringUtils and ArrayList to return string without excess. See how I use it:

public String toString() {
    List<String> ret = new ArrayList<String>();
    Node current = head;
    while (current.getNext() != null) {
        current = current.getNext();
        ret.add(current.get());
    }

    return "[" + StringUtils.join(ret, ",") + "]";
}

Upvotes: 2

Md. Nasir Uddin Bhuiyan
Md. Nasir Uddin Bhuiyan

Reputation: 1596

Try this one:

public String toString() {
  String ret = "[";
  Node current = head;
  while(current.getNext() != null) {
    current = current.getNext();
    ret += current.get() + ", ";
  }

  ret=ret.substring(0,ret.length()-2);
  return ret + "]";
}

Upvotes: 0

dognose
dognose

Reputation: 20909

Maybe you should consider to have a look at the toString() Method of Javas AbstractCollection. This would give you a good idea how to use StringBuilder for this purpose:

  /**
     * Returns a string representation of this collection.  The string
     * representation consists of a list of the collection's elements in the
     * order they are returned by its iterator, enclosed in square brackets
     * (<tt>"[]"</tt>).  Adjacent elements are separated by the characters
     * <tt>", "</tt> (comma and space).  Elements are converted to strings as
     * by {@link String#valueOf(Object)}.
     *
     * @return a string representation of this collection
     */
    public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }

Upvotes: 0

Vishrant
Vishrant

Reputation: 16688

use this ret.substring(0, ret.length() - 1)

@Override
public String toString() {
      String ret = "[";
      Node current = head;
      while(current.getNext() != null) {
        current = current.getNext();
        ret += current.get() + ", ";
      }

      ret = ret.substring(0, ret.length() - 1);

      return ret + "]";
}

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109613

public String toString() {
  StringBuilder ret = new StringBuilder('[');
  Node current = head;
  while(current.getNext() != null) {
    current = current.getNext();
    ret.append(current.get()).append(", ");
  }
  if (ret.length() > 1) {
      ret.delete(ret.length() - 2, ret.length());
  }
  return ret.append(']').toString();
}

One has to guard for an empty list so it remains []. That leaves two possibilities: a boolean flag or deleting afterwards. For performance better use a StringBuilder. To some degree the compiler will will translate String concatenations to StringBuilder, but here not entirely so.

Upvotes: 0

locoyou
locoyou

Reputation: 1697

You can use substring to remove the last 2 characters.

return ret.substring(0, ret.length()-2)+"]"

Upvotes: 1

Simon Tendick
Simon Tendick

Reputation: 40

I did not test it but this should work.

public String toString() {
  String ret = "[";
  Node current = head;
  while(current.getNext() != null) {
    current = current.getNext();
    ret += current.get();
    if(current.getNext() != null) ret += ", ";
  }
  return ret + "]";
}

Upvotes: 2

Related Questions