Thursday, July 12, 2018

Java print array of integers joined by spaces

One solution is to iterate over the array and print the desired string. Another solution is just using substring as following:


String result = Arrays.toString(arr);
System.out.println(" "+result.substring(1, result.length()-1));

By iterating also you can get this result as following:


for (int i=0;i    System.out.print(arr[i] + " ");
}

Or using regex, you can replace first and last characters as following:


System.out.println(" " + Arrays.toString(arr).replaceAll("^.|.$", ""));

You can also use StringUtils(commons-lang) which is null safe:


StringUtils.substringBetween(Arrays.toString(arr), "[", "]");

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...