Sahand
Sahand

Reputation: 8360

how to not insert extra space at the end or beginning of space separated strings

I want to represent a list [1,2,3,4] like "\"1 2 3 4\"". Note the escaped quotes and the lack of a space between them and their neighbouring numbers. How can I achieve this? It's such a trivial thing, but it's tricky since I'm working with a TreeSet, not an array. Is this even possible with a for loop or do I have to resort to using the TreeSet iterator?

public String positionsRep(TreeSet<Integer> positions){
    StringBuilder s = new StringBuilder("");
    s.append("\"");
    for(Integer pos: positions){
        posStr = Integer.toString(pos);
        s.append(posStr);
        s.append(" ");
    }   
    s.append("\"");
    return s.toString();
}  

Upvotes: 0

Views: 189

Answers (2)

khennouche faycal
khennouche faycal

Reputation: 51

You can generate an Array from that TreeSet and the use the string properties to join the elements by a space and then add the special char that you need

Example:

TreeSet<String> playerSet = new TreeSet<String>();
    playerSet.add("1");
    playerSet.add("2");
    playerSet.add("3");
    playerSet.add("4");

    StringBuilder sr = new StringBuilder();
    sr.append("\"").append(String.join(" ", new ArrayList<String> (playerSet))).append("\"");
    System.out.println(sr.toString());

Upvotes: 0

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

Just treat the first number a bit differently:

public String positionsRep(TreeSet<Integer> positions){
    StringBuilder s = new StringBuilder("");
    s.append("\"");
    boolean isFirst = true;
    for(Integer pos: positions){
        if (!isFirst) {
            s.append(" ");
        }
        posStr = Integer.toString(pos);
        s.append(posStr);
        isFirst = false;
    }   
    s.append("\"");
    return s.toString();
}

However, it might be better to just use a StringJoiner instead of the StringBuilder, it does exactly what you want if initialized with (" ", "\"", "\""). This should look somehow like that:

StringJoiner sj = new StringJoiner(" ", "\"", "\"");
for (Integer i: positions) {
    sj.add(i.toString());
}
String result = sj.toString();

Or even shorter using streams:

import java.util.stream.Collectors;

positions.stream().map(Integer::toString).collect(Collectors.joining(" ", "\"", "\""));

Upvotes: 2

Related Questions