0

The essence of the problem is: Implement a public static addPrefix() method that takes an array of strings and a string prefix as input and returns a new array in which the given prefix is added to each element of the original array. A space is automatically added after the prefix.

How the program should work:

String[] names = {"John", "Smit", "Karl"};
var namesWithPrefix = App.addPrefix(names, "Mr.");

System.out.println(Arrays.toString(namesWithPrefix));
// => ["Mr. John", "Mr. Smit", "Mr. Karl"]

System.out.println(Arrays.toString(names)); //  The original array does not change

// => ["John", "Smit", "Karl"]

Here is my code:

public class App {
   
    public static String[] addPrefix(String[] names, String[] prefixes){
       
       String[] result= new String[names.length];
       String sequence =""+ names[0]+prefixes[0];
       result[0]="["+ sequence+"]";

       for(int i=1; i<names.length;i++){
           sequence+=", "+names[i];
           result[i] ="[" + sequence +"]";
       }
       return result;
    }
    
}
  • starting with first line, how is the argument `"Mr."` expected to be assigned to the parameter of type `String[]` - first is a single string, second an array? How is `names[0]+prefix[0]` expected to have the prefix IN FRONT of the name? Actually: WHAT is the question? – user16320675 Jun 15 '22 at 16:02
  • If the question was "How to implement this with Java 8 streams?" --> `var namesWithPrefix = Arrays.stream(names).map((prefix+" ")::concat).toArray(String[]::new);` – user16320675 Jun 15 '22 at 16:11

1 Answers1

0

This is how I'd do it based on the requirements.

Create the result array, loop through the original names by index and assign the prefix + space + current original name to the corresponding result array slot.

public static String[] addPrefix(String[] names, String prefix) {
    String[] result = new String[names.length];
    for (int i = 0; i < names.length; i++) {
        result[i] = prefix + " " + names[i];
    }
    return result;
}
akarnokd
  • 69,132
  • 14
  • 157
  • 192