Home > Enterprise >  Function that takes in an int array and returns a string array with all elements converted to string
Function that takes in an int array and returns a string array with all elements converted to string

Time:05-07

Trying to make a function that takes in an int[] numbers as input and returns a String[] with the values of numbers converted to Strings using the function. Not sure how to continue or how to convert ints to strings.

CodePudding user response:

You can use Integer#toString to convert the integer to a string:

int[] nums = ...;
String[] stringNums = new String[nums.length]
for(int i = 0; i < nums.length; i  ){
    stringNums[i] = Integer.toString(nums[i]);
}
return stringNums;

CodePudding user response:

int[] foo = ...

String[] bar = new String[foo.length];

for (int i = 0; i < foo.length; i  = 1) {

    bar[i] = String.valueOf(foo[I];
}

Next time you could probably google search too :)

CodePudding user response:

Here's an alternative streams-based approach:

    int[] a = {1,2,3,4,5};
    String[] b = String[] b = Arrays.stream(a).mapToObj(String::valueOf).toArray(String[]::new);
  1. Make an IntStream containing the input data
  2. Convert to a stream of strings
  3. Convert to a String[]
  • Related