Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an int array to a String array

Tags:

So I have this "list" of ints. It could be a Vector, int[], List<Integer>, whatever.

My goal though is to sort the ints and end up with a String[]. How the int array starts out as is up in the air.

ex: Start with:{5,1,2,11,3} End with: String[] = {"1","2","3","5","11"}

Is there anyway to do this without a for loop? I have a for loop now for collecting the ints. I would rather skip doing another for loop.

like image 396
dev4life Avatar asked Sep 01 '10 15:09

dev4life


People also ask

Can we convert int array to string?

Arrays. toString(int[]) method returns a string representation of the contents of the specified int array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]").

How do I convert a number array to a string?

To convert an array of numbers to an array of strings, call the map() method on the array, and on each iteration, convert the number to a string. The map method will return a new array containing only strings.

Can we convert array to string?

Convert Array to String. Sometimes we need to convert an array of strings or integers into a string, but unfortunately, there is no direct method to perform this conversion. The default implementation of the toString() method on an array returns something like Ljava. lang.


1 Answers

int[] nums = {5,1,2,11,3}; //List or Vector Arrays.sort(nums); //Collections.sort() for List,Vector String a=Arrays.toString(nums); //toString the List or Vector String ar[]=a.substring(1,a.length()-1).split(", "); System.out.println(Arrays.toString(ar)); 

UPDATE:

A shorter version:

int[] nums = {-5,1,2,11,3}; Arrays.sort(nums); String[] a=Arrays.toString(nums).split("[\\[\\]]")[1].split(", ");  System.out.println(Arrays.toString(a));   
like image 169
Emil Avatar answered Oct 10 '22 09:10

Emil