1

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
  • for something simple like this perhaps use: Arrays.toString((Arrays.copyOfRange(a,0,2))).replaceAll("\\s+|\\[|\\]|,", "");. Here we simply remove the characters we don't want that the Arrays.toString() method produces with the String.replaceAll() method utilizing a Regular Expression. The regular expression is basically saying replace all whitespaces (\\s+) if encountered or replace all open square brackets (\\[) if encountered or replace all close square brackets (\\]) if encountered or replace all commas (,) if encountered and replace them with a null string (nothing). Commented Dec 18, 2017 at 6:22
  • @AxelH - I never said it was simpler. It's just another way among many ways. But comma is not present in the provided array ;) Commented Dec 18, 2017 at 6:26
  • @AxelH - Uhhh...I see...English is obviously not your native language. Commented Dec 18, 2017 at 6:47

3 Answers 3

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));
Sign up to request clarification or add additional context in comments.

Comments

0

The following should work:

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

Comments

-1

Use this part for your code:

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

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.