简体   繁体   中英

String text parse using split

I have a String which is of form (name.surname/city name2.surname2.city2 [...]). I have already created the person class and the constructor plus override method toString() which should return the name, surname and city.

From main class I have created a new String[] using the split for the related regex present"[./ ]+". Then I have created a personArray using that length/3.

At run I need to have the below output:

name surname city
name2 surname2 city2
[...]

OR

Name is name, Surname is surname, City is city1
Name is name2, Surname is surname2, City is city2
[...]

Unable to have the expected output.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String text = new String("John.Wick/Budapest Michael.Bolton/Manchester Ivan.Perisic/Zagreb Vladimir.Putin/Moscow");
        String[] textArray = text.split("[./ ]+");
        Person [] personArray = new Person[textArray.length/3];

        for (String s : textArray)
            for (int i = 0; i < textArray.length; i+=3) {
                System.out.print(s);
            }
       //show person data
       for(Person person : personArray){
          System.out.println(person);
        }
    }
}

Person class

public class Person {
    private final String surname;
    private final String name;
    private final String city;

    public Person(String surname, String name, String city) {
        this.surname = surname;
        this.name = name;
        this.city = city;
    }
    @Override
    public String toString() {
        return "Surname = "+ surname + " " +
                "Name = " + name + " " +
                "City = " + city + " ";
    }
}

==============

As you never add anything in personArray your output is correct.

Now for each box, you need to instanciate a Person with correct strings, use their position for that

String text = "John.Wick/Budapest Michael.Bolton/Manchester Ivan.Perisic/Zagreb Vladimir.Putin/Moscow";
String[] textArray = text.split("[./ ]+");
Person[] personArray = new Person[textArray.length / 3];

for (int i = 0; i < personArray.length; i++) {
    personArray[i] = new Person(textArray[i * 3], textArray[i * 3 + 1], textArray[i * 3 + 2]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM