Skip to content
Advertisement

How can I split string elements of an array and add them to another?

Using an array list of names, I am trying to split the first names and surnames using a for loop. The code works but when splitting the names using a substring it goes from 0-x (x being the space between the names) but it reads from 0 each time and adds each name multiple times until it completes. How can I run it from the next element each time to skip the name previously split and added?

public static void main(String[] args) {

    String [] name_list = {"lee momo", "michael jesus", "kim danger", "dean habbo"};

    ArrayList<String> firstNames = new ArrayList<String>();
    ArrayList<String> surnames = new ArrayList<String>();

    for(int i = 0; i < name_list.length; i++){
        int x = name_list[i].indexOf(" ");
        String firstName = name_list[i].substring(0, x);
        firstNames.add(firstName);

        for(int j = 0; j < name_list.length; j++){
            int y = name_list[i].indexOf(" ");
            String surname = name_list[i].substring(x);
            surnames.add(surname);
        }
        
        System.out.println(firstNames.toString());
        System.out.println(surnames.toString());

    }
}

For example the output of first names is like this: lee lee, michael lee, michael, kim lee, michael, kim, dean

Advertisement

Answer

Fix

You need only one loop, to extract both

String[] name_list = {"lee momo", "michael jesus", "kim danger", "dean habbo"};
ArrayList<String> firstNames = new ArrayList<>();
ArrayList<String> surnames = new ArrayList<>();
for (int i = 0; i < name_list.length; i++) {
    int x = name_list[i].indexOf(" ");
    String firstName = name_list[i].substring(0, x);
    firstNames.add(firstName);
    String surname = name_list[i].substring(x + 1);
    surnames.add(surname);
}
System.out.println(firstNames); // [lee, michael, kim, dean]
System.out.println(surnames); // [momo, jesus, danger, habbo]

Improve

  • use String.split()
  • use a for each loop
for (String s : name_list) {
    String[] parts = s.split("\s+");
    firstNames.add(parts[0]);
    surnames.add(parts[1]);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement