How can I split a string, then use the parts to create an object, and then create an array with these objects?

huangapple go评论129阅读模式
英文:

How can I split a string, then use the parts to create an object, and then create an array with these objects?

问题

我需要解决一个有点复杂的任务,但似乎做得不对。

我有以下字符串:

String text = "John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";

简而言之,程序流程应该如下:

  • 将给定的字符串拆分成多个部分以获取名字、姓氏和城市;

  • 使用获取的数据创建Person对象;

  • 将获取的Person对象放入Person[]数组中;

  • 循环遍历数组并打印出其数据。

对于给定的字符串,输出应该如下所示:

  • John Davidson Belgrade

  • Michael Barton Krakow

  • Ivan Perkinson Moscow

这是主要代码:

public class Program {
    public static void main(String[] args) {
        String text = "John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";
        String[] array1 = text.split("[/. ]");
        for (String s : array1) {
            System.out.println(s);
        }
        Person[] array = new Person[3];
        for  (int i=0; i < 3; i++)
        {
            array[i] = new Person();
        }
        array[0] = new Person("John", "Davidson","Belgrade");
        array[1] = new Person("Michael", "Barton", "Krakow");
        array[2] = new Person("Ivan", "Perkinson","Moscow");
        for (Person value : array) {
            System.out.println(value);
        }
    }
}

这是Person类:

public class Person {
    public String name;
    public String surname;
    public String city;
    public Person(){};
    public Person(String name, String surname, String city){
        this.name = name;
        this.surname = surname;
        this.city = city;
    }
    public String getInfo() {
        return "Name: " + this.name + "\n" + "Surname: " + this.surname + "\n" + "City: " + this.city;
    }
}

不幸的是,结果是这样的:

John

Davidson

Belgrade

Michael

Barton

Krakow

Ivan

Perkinson

Moscow

Person@5f184fc6

Person@3feba861

Person@5b480cf9

我做错了什么?我甚至不知道最后三个条目是什么...

PS:对于我的糟糕英语,非母语者请谅解。

英文:

I need to solve a somewhat complicated task, but I don't seem to get it right.

I have the following String:

String text = &quot;John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow&quot;;

In short, the program flow should be like this:

  • split the given String into multiple parts to get first name, last name, and cities;

  • use the obtained data to create the Person object;

  • put the obtained Person objects into a Person[] array;

  • loop through an array and print out its data.

On output, the following display should be obtained for the string given as an example:

  • John Davidson Belgrade

  • Michael Barton Krakow

  • Ivan Perkinson Moscow

This is the main code:

public class Program {
    public static void main(String[] args) {
        String text = &quot;John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow&quot;;
        String[] array1 = text.split(&quot;[/. ]&quot;);
        for (String s : array1) {
            System.out.println(s);
        }
        Person[] array = new Person[3];
        for  (int i=0; i &lt; 3; i++)
        {
            array[i] = new Person();
        }
        array[0] = new Person(&quot;John&quot;, &quot;Davidson&quot;,&quot;Belgrade&quot;);
        array[1] = new Person(&quot;Michael&quot;, &quot;Barton&quot;, &quot;Krakow&quot;);
        array[2] = new Person(&quot;Ivan&quot;, &quot;Perkinson&quot;,&quot;Moscow&quot;);
        for (Person value : array) {
            System.out.println(value);
        }
    }
}

This is the Person class:

public class Person {
    public String name;
    public String surname;
    public String city;
    public Person(){};
    public Person(String name, String surname, String city){
        this.name = name;
        this.surname = surname;
        this.city = city;
    }
    public String getInfo() {
        return &quot;Name: &quot; + this.name + &quot;\n&quot; + &quot;Surname: &quot; + this.surname + &quot;\n&quot; + &quot;City: &quot; + this.city;
    }
}

Unfortuntaley, the result is this:

John

Davidson

Belgrade

Michael

Barton

Krakow

Ivan

Perkinson

Moscow

Person@5f184fc6

Person@3feba861

Person@5b480cf9

What am I doing wrong? I don't know even what the last three entries are...

PS: Sorry for my bad English, not a native speaker.

答案1

得分: 2

String text = "John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";
String[] names = text.split(" ");
List<String> output = Arrays.stream(names)
                            .map(x -> x.replaceAll("[./]", " "))
                            .collect(Collectors.toList());
System.out.println(output);

// [John Davidson Belgrade, Michael Barton Krakow, Ivan Perkinson Moscow]
英文:

Split on space first, the iterate the array of names and do a replacement:

<!-- language: java -->

String text = &quot;John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow&quot;;
String[] names = text.split(&quot; &quot;);
List&lt;String&gt; output = Arrays.stream(names)
                            .map(x -&gt; x.replaceAll(&quot;[./]&quot;, &quot; &quot;))
                            .collect(Collectors.toList());
System.out.println(output);

// [John Davidson Belgrade, Michael Barton Krakow, Ivan Perkinson Moscow]

答案2

得分: 1

你试图做的事情是错误的,因为你无法使用固定大小初始化数组,因为你不知道字符串中有多少人,所以最好使用ArrayList。

public static void main(String[] args) {
    String text = "John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";
    String[] personsString = text.split(" ");
    List<Person> persons = new ArrayList<Person>();
    
    for (String ps : personsString) {
        String firstName = ps.split("/")[0].split("\\.")[0];
        String lastName = ps.split("/")[0].split("\\.")[1];
        String city = ps.split("/")[1];
        persons.add(new Person(firstName, lastName, city));        
    }
    
    for (Person person : persons) {
        System.out.println(person.getInfo());
    }
}
英文:

What are you trying to do was wrong
you cant initialise the array with a fixed size cause you dont know how much persons are present in the string, so you better use an arrayList

public static void main(String[] args) {
        String text = &quot;John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow&quot;;
        String[] personsString = text.split(&quot; &quot;);
        List&lt;Person&gt; persons = new ArrayList&lt;Person&gt;();
        
        for (String ps : personsString) {
        	String firtname = ps.split(&quot;/&quot;)[0].split(&quot;\\.&quot;)[0];
        	String lastname = ps.split(&quot;/&quot;)[0].split(&quot;\\.&quot;)[1];
        	String city = ps.split(&quot;/&quot;)[1];
        	persons.add(new Person(firtname, lastname, city));        	
        }
        
        for (Person person : persons) {
            System.out.println(person.getInfo());
        }
    }

答案3

得分: 0

以下是翻译好的部分:

如果您想要将前面两个答案合并成一个Person对象列表,可以像这样操作:

public static void main(String[] args) {
    // 您的示例输入
    String text = "John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";
    // 按任意数量的空格进行拆分
    String[] personInfos = text.split("\\s+");
    // 流式处理结果
    List<Person> persons = Arrays.stream(personInfos)
        // 拆分字符串以提取信息部分并从中创建Persons
        .map(x -> new Person(
            // 通过点拆分,第一个元素是姓名
            x.split("\\.")[0],
            // 通过斜杠拆分上述操作的第二个元素提供姓氏
            x.split("\\.")[1].split("/")[0],
            // 和城市
            x.split("\\.")[1].split("/")[1]
        ))
        .collect(Collectors.toList());
    // 打印每个人的toString()
    persons.forEach(System.out::println);
}

假设您按照以下方式重写了Person::toString()...

public class Person {
    
    
    @Override
    public String toString() {
        return String.format("%s, %s (%s)", surname, name, city);
    }
}

...输出将如下所示:

Davidson, John (Belgrade)
Barton, Michael (Krakow)
Perkinson, Ivan (Moscow)
英文:

I would split on space(s) first, because that operation already separates the values per person.

If you want to combine both of the previous answers to have a list of Person objects, you could do it like this:

public static void main(String[] args) {
	// your example input
	String text = &quot;John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow&quot;;
	// split by arbitrary amount of whitespaces
	String[] personInfos = text.split(&quot;\\s+&quot;);
	// stream the result
	List&lt;Person&gt; persons = Arrays.stream(personInfos)
			// and split the Strings to extract the info parts and create Persons from those
            .map(x -&gt; new Person(
            			// split by dot has name as first element
                		x.split(&quot;\\.&quot;)[0],
                		// splitting the second element of above operation by slash provides surname
                		x.split(&quot;\\.&quot;)[1].split(&quot;/&quot;)[0],
                		// and city
                		x.split(&quot;\\.&quot;)[1].split(&quot;/&quot;)[1]
    				)
            ).collect(Collectors.toList());
	// print each person&#39;s toString()
	persons.forEach(System.out::println);
}

Provided you override the Person::toString() as follows…

public class Person {
    
    
    @Override
    public String toString() {
    	return String.format(&quot;%s, %s (%s)&quot;, surname, name, city);
    }
}

… the output will be this:

Davidson, John (Belgrade)
Barton, Michael (Krakow)
Perkinson, Ivan (Moscow)

huangapple
  • 本文由 发表于 2023年8月10日 17:46:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76874550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定