Search code examples
javaarraysstringfor-loopprefixes

How to add and modify prefix in Java, using String arrays?


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;
    }
    
}

Solution

  • 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;
    }