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

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.

3 answers

  • answered 2022-05-07 00:29 Saner Cakir

    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 :)

  • answered 2022-05-07 00:29 Spectric

    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;
    

  • answered 2022-05-07 01:03 Jim Garrison

    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[]

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum