parse Vector string into a String?

2019-09-01 01:15发布

问题:

How can i parse a Vector to a normal String?

i.e

Vector newfollowerlist = "name1, name2, name3, name4";

As soon i output the vector string it looks like this;

[name1, name2, name3, name4]

and i want to delete the [] of the line so i thought about parsing the vector string to a normal String and delete the [] by:

String stringWithoutArraySymbols = String VectorHolder.replaceAll("[",""); 
String stringWithoutArraySymbols = String VectorHolder.replaceAll("]","");

How can i actually parse it or is there an easier way to do this?

回答1:

A slight variation

String s = newfollowerlist.toString();
System.out.println(s.substring(1, s.length()-1));

You know the format of newfollowerlist.toString() so its easy enough to get your desired format. Should work if newfollowerlist is a Vector, List, Set or many other Collection types.



回答2:

As I mentioned, do not use Vector. Read about the Java collections API.

I will use the Collection interface.

With Java 8:

final String joined = things.stream().collect(Collectors.joining(","));

With Java 7:

final Iterator<String> iter = things.iterator();
final StringBuilder sb = new StringBuilder();
sb.append(iter.next());
while (iter.hasNext()) {
    sb.append(",").append(iter.next());
}
final String joined = sb.toString();