1
int arr[] = new int[10];
for(int i=0;i<10;i++){
   arr[i]=s.nextInt();
}
Arrays.sort(arr);
System.out.println(" "+Arrays.toString(arr));

my input is :

98 7 6 5 4 32 14 5 1 7

my output is :

[1, 4, 5, 5, 6, 7, 7, 14, 32, 98]

but i want to print my output as sorted number only but not with [ ] and commas what would be the required solution

Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35

3 Answers3

4

Just loop over the array, and print each number.

for (int i: arr) {
  System.out.print(i);
  System.out.print(" ");
}
System.out.println();
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • ..this one worked perfectly..without scratching my mind..but why we are printing index value since we have to print element of that index will you please explain – ravi kumar sharma Aug 15 '18 at 08:43
  • In a for-each-loop the `i` is not the index, but the element of the collection you are iterating over. This is different from `for (int i=0; i<10; i++)` – Thilo Aug 15 '18 at 13:54
  • This has a trailing space which might not be desirable. – Matej Novosad Sep 15 '22 at 10:09
4

Use replaceAll to replace [ and ] with empty string:

System.out.println(" " + Arrays.toString(arr).replaceAll("[\\[|\\]]", ""));
xingbin
  • 27,410
  • 9
  • 53
  • 103
3

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<arr.length;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), "[", "]");
Kaushal28
  • 5,377
  • 5
  • 41
  • 72