1

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.

3 Answers 3

9

Use toString in Arrays class

Arrays.toString(easy);
Sign up to request clarification or add additional context in comments.

1 Comment

+1, note that in case of more than 1-dimensional arrays better to use Arrays.deepToString(a)
7

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.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.