Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading