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
  • 16,436
  • 7
  • 61
  • 102
user2477501
  • 61
  • 1
  • 1
  • 1

3 Answers3

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();
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
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
  • 133,369
  • 30
  • 199
  • 275
2

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

Andreas
  • 5,393
  • 9
  • 44
  • 53
Developer
  • 183
  • 12