-3

i have a java String like:
String mine = "Role = Student; DateFrom = 21/12/2020; DateTo = 10/01/2021;".

I have my Java Class called Rule that has the same properties contained in the mine String, i.e:

public class Rule {  
    private String role; 
    private Calendar dateFrom; 
    private Calendar dateTo;

    .....
}

How can I extract the data from the string and set it in the corresponding property? After this i wanna have the following scenario:

Rule.getRole(); // Student  
Rule.getDateFrom(); // 21/12/2020
Rule.getDateTo(); // 10/01/2021

2 Answers2

1

I mean 2-steps split and determine the current key:

String mine = "Role = Student; DateFrom = 21/12/2020; DateTo = 10/01/2021;";

String[] pairs = mine.split(";");
for (String pair : pairs) {
    String[] couple = pair.split("=");
    
    String key = couple[0].trim();
    String value = couple[1].trim();
    
    if (key.equalsIgnoreCase("role")) 
        roleValue = value;
    else if (key.equalsIgnoreCase("DateFrom")) )
      // ... and so on
}

The example here intentionally does not take into account null values, array lengths and String to Calendar conversion.

fantaghirocco
  • 4,761
  • 6
  • 38
  • 48
1

Use org.apache.commons.lang3.StringUtils conviniene methods for string parsing. Also change Calendar to java.time.LocalDate. Here is a working example:

Rule.java

import java.time.LocalDate;
import java.util.StringJoiner;

public class Rule {
  private String role;
  private LocalDate dateFrom;
  private LocalDate dateTo;

  public Rule(final String role, final LocalDate dateFrom, final LocalDate dateTo) {
    this.role = role;
    this.dateFrom = dateFrom;
    this.dateTo = dateTo;
  }

  @Override
  public String toString() {
    return new StringJoiner(", ", Rule.class.getSimpleName() + "[", "]")
        .add("role='" + role + "'")
        .add("dateFrom=" + dateFrom)
        .add("dateTo=" + dateTo)
        .toString();
  }
}

Main.java

import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
  public static void main(String[] args) {
    String mine = "Role = Student; DateFrom = 21/12/2020; DateTo = 10/01/2021;";

    String role = StringUtils.substringBetween(mine, "Role =", ";").trim();
    String dateFrom = StringUtils.substringBetween(mine, "DateFrom =", ";").trim();
    String dateTo = StringUtils.substringBetween(mine, "DateTo =", ";").trim();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    LocalDate localDateFrom = LocalDate.parse(dateFrom, formatter);
    LocalDate localDateTo = LocalDate.parse(dateTo, formatter);
    Rule rule = new Rule(role, localDateFrom, localDateFrom);
    System.out.println(rule);
  }
}

Output (You can format the date as per your preference)

Rule[role='Student', dateFrom=2020-12-21, dateTo=2020-12-21]
Tushar
  • 670
  • 3
  • 14