Akino Akino - 10 months ago 60
Java Question

Java construrctor with string params

How can I extract attributes values from the string parameter ?

public class Pays{
public Pays(String paysDescriptions) {

pays= new Pays("p1:Europe:France, p2:Amerique:Canada");


I gave an answer below to people who have never used this type of constructor (like me :p ) and who may need some explanations.

Answer Source

You should try using String.split(String regex) API.

  1. Break the parameter paysDescriptions using comma(,) as regex, then
  2. Break the individual items using colon(:) as regex


public Pays(String paysDescriptions) {
    String[] split_1 = paysDescriptions.split(",");
    for (String split : split_1) {
        String[] split_2 = split.split(":");
        for (String sp : split_2) {
            System.out.println(sp); // use sp.trim() if spaces after comma
                                    // not required.