How correctly (field-value) to parse a string like:

String line = "Fruit: apple=23, orange=43;" 
  • 2
    Give an example of the complete data format you need to parse. Or there will be nothing else, just the way you brought in the question? - Peter Samokhin
  • There is a class Fruit (String name, int price), and there is a string. You need to parse the string so that you can later put the data into the object. There will be one, as written in the question. - Matty

1 answer 1

Nothing complicated, the example below can be refined and make it universal (at the moment it only parses the example you cited).

 String strings = "Fruit: apple=23, orange=43;Fruit: apple=23, orange=43;Fruit: apple=23, orange=43;Fruit: apple=23, orange=43;"; List<Fruit> fruits = new ArrayList<>(); for (String str: strings.split(";")) { String necessaryPart = str.substring(str.indexOf(' ')).trim(); String[] fruitsStrings = necessaryPart.split(", "); for (String fruitStr : fruitsStrings) { String[] values = fruitStr.split("="); Fruit fruit = new Fruit(values[0], Integer.parseInt(values[1])); fruits.add(fruit); } } System.out.println(fruits); 

Your class:

 class Fruit { private String name; private int price; public Fruit(String name, int price) { this.name = name; this.price = price; } // getters, setters @Override public String toString() { return "Fruit{" + "name='" + name + '\'' + ", price=" + price + '}'; } } 
  • Thank! And if the lines with fruit will be 3? - Matty
  • @Matty what lines? You mean, like this: Fruit: apple=23, orange=43, banana=100, raspberry=1337; ? Yes, as many as you like. - Peter Samokhin
  • Fruit: apple = 23, orange = 43, banana = 100, raspberry = 1337; Fruit: apple = 23, orange = 43, banana = 100, raspberry = 1337; Fruit: apple = 23, orange = 43, banana = 100, raspberry = 1337; - Matty
  • That is, three Fruit - three copies of the class Fruit - Matty
  • @Matty yes, as you can see, each iteration creates a new instance of the class. If the answer satisfies you, accept it as true - for this there is a tick just to the left of the answer itself. - Peter Samokhin 2:53 pm