How correctly (field-value) to parse a string like:
String line = "Fruit: apple=23, orange=43;" 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 + '}'; } } Fruit: apple=23, orange=43, banana=100, raspberry=1337; ? Yes, as many as you like. - Peter SamokhinSource: https://ru.stackoverflow.com/questions/815508/
All Articles