Super man Super man - 2 months ago 7
Java Question

returning String[ ] array in java method without commas

I am solving a problem in

TopCoder
where I need to write a method which must return
String[]
. This is my method, and its working without any error:

public static String[] decode(String encoded)
{
char[] test = encoded.toCharArray();
int[] decode_arr = new int[test.length];
String[] result = new String[2];
boolean flag= false;
for(int i=0;i<2;i++)
{
flag = false;
decode_arr[0] = i;
decode_arr[1] = Character.getNumericValue(test[0])-decode_arr[0];

for(int x=2;x<test.length;x++)
{
decode_arr[x] = Character.getNumericValue(test[x-1]) - decode_arr[x-2]-decode_arr[x-1];
if(decode_arr[x]>1 || decode_arr[x]<0)
flag=true;
}
if(!flag)
result[i] = Arrays.toString(decode_arr);
else
result[i] = "NONE";

//System.out.println(Arrays.toString(decode_arr));
decode_arr = null;
decode_arr = new int[test.length];
}

return result;

}


Now the problem is the compiler expects values without commas, for instance if the output is:

"01101001101101001101001001001101001",
"10110010110110010110010010010110010"


What I do obtain is:

[0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0
, 0, 1, 1, 0, 1, 0, 0, 1]
[1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0
, 1, 0, 1, 1, 0, 0, 1, 0]


Am I missing any common tweaks or am I supposed to trim the output and submit it the way it's supposed to be? Kindly help!

Answer

It's what Arrays.toString() does. Show's the group of values clearly the same way as List. In case of:

int[] array = {11, 2}; // printed as "112" afterwards

..you cannot clearly see if it's the array of [11, 2], or [1, 12] or only [112].

However if you desire that kind of output, try to replace all unwanted characters with an empty character:

String out = Arrays.toString(array).replace(", ", "").replace("[", "").replace("]", "");

In case of having [] characters as some of values, I recommend you better this safe way:

String arrayAsString = Arrays.toString(array);
String out = arrayAsString.substring(1,arrayAsString.length()-1).replace(", ","");