0

How to concatenate two char arrays in java ?

char info[]=new char[10]; char data[]=new char[10]; char result[]=new char[40]; 

I need to concatenate info and data, and store the concatenation in result:

result=info+data;

How to do this?

2

3 Answers 3

10

It depends I guess. The simpler approach would be just to convert the char arrays to a String and concaternate the Strings.

A better approach would be to use StringBuilder

char info[] = new char[10]; char data[] = new char[10]; // Assuming you've filled the char arrays... StringBuilder sb = new StringBuilder(64); sb.append(info); sb.append(data); char result[] = sb.toString().toCharArray(); 
Sign up to request clarification or add additional context in comments.

6 Comments

If he wants the output as a string that is a nice approach.
I don't think you want to append result. He says he wants result = info + data. In your case, the last line should be result = sb.toString().toCharArray();
@assylias Yeah I thought that to, I also thought that sb.toString().toCharArray() to get the character array back. This of course assumes the OP wants to only use char arrays ;)
@AleksG Ah, that's true, missed that. Thanks
Love down votes without comment, makes me all warm and fuzzy inside :P
|
5

try this

char result[] = new char[info.length + data.length]; System.arraycopy(info, 0, result, 0, info.length); System.arraycopy(data, 0, result, info.length, data.length); 

Comments

2

Just found one-line solution from the old Apache Commons Lang library: ArrayUtils addAll()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.