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?

skomisa
  • 14,478
  • 7
  • 54
  • 90
user2477501
  • 61
  • 1
  • 1
  • 1

3 Answers3

9

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();
MadProgrammer
  • 336,120
  • 22
  • 219
  • 344
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);
Evgeniy Dorofeev
  • 129,181
  • 28
  • 195
  • 266
2

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

Andreas
  • 5,050
  • 8
  • 42
  • 51
Developer
  • 173
  • 12