Getting sub array of character array

时间:2017-12-18 05:40:28

标签: java

Suppose I have character array containing elements {'.','-','.','-','-'}. And I want to retrieve sub array {'.','-'} and convert this into string as ".-". I have used the following statement

String temp = Arrays.toString((Arrays.copyOfRange(s,0,2)));

But when I print temp then it prints [.,-] that is temp = "[.,-]".
So temp is impure string and I only want {'.','-'} these character in temp that is temp =".-".

What should I do?

3 个答案:

答案 0 :(得分:2)

Using Arrays.toString will build a String like [ <cell0>, <cell1>, <cell2>, ..., <celln>] as explain in the doc :

Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(char). Returns "null" if a is null.

This explains why you get "[., -]" But you can correct String representation of a char[] with the constructor

public String(char[] value)

Allocates a new String so that it represents the sequence of characters currently contained in the character array argument [...]

Or the static method valueOf

public static String valueOf(char[] data)

Returns the string representation of the char array argument [...]

String s1 = new String(Arrays.copyOfRange(s,0,2));
String s2 = String.valueOf(Arrays.copyOfRange(s,0,2));

答案 1 :(得分:0)

The following should work:

String temp = String.valueOf(Arrays.copyOfRange(s,0,2));

答案 2 :(得分:-1)

Use this part for your code:

String temp=String.valueOf((Arrays.copyOfRange(s,0,2)));