Reputation: 401
I need to convert a string vector in a simple string. I do not know how to proceed. I tried various solutions such as
for(int i=1; i < easy.length; i++){
easyPuzzle = easy[i].toString();
}
System.out.println(" " + easyPuzzle);
but this solution prints only the ith element and not the entire string vector.
Upvotes: 1
Views: 337
Reputation: 328598
You keep reassign a new value to easyPuzzle
when you really want to concatenate:
easyPuzzle += easy[i].toString();
If easy.length
is large, it might make sense to use a StringBuilder which is more efficient at concatenating than String:
StringBuilder builder = new StringBuilder();
for(int i=1; i < easy.length; i++){
builder.append(easy[i].toString());
}
easyPuzzle = builder.toString();
Also by starting your for loop at i=1
you exclude the first item. Not sure if it is on purpose or not. If not, start at i = 0
.
Alternatively, to save the pain of writing the loop yourself, you can use @Manoj's answer which replaces your code by one line.
Upvotes: 7
Reputation: 33495
I recommend to you use StringBuilder
with append(<data>)
method and then convert it to String
.
StringBuilder data = new StringBuilder();
for(int i = 1; i < easy.length; i++){
data.append(easy[i].toString());
}
easyPuzzle = data.toString();
String
is immutable so work with it is much more consume. When you work with String
, i recommend to you use StringBuilder
, is more effective and faster.
Update: @Manoj answer is very usefull.
Upvotes: 2