how to parse and convert a text in dart?

This does look like something that is best handled by a RegExp.

RegExp _tempRE = RegExp(r"\[\{(-?\d+(?:\.\d+)?)°\}\{([CF])\}\]");
String convertTemperaturesToCelsius(String input) {
  return input.replaceAllMapped(_tempRE, (m) {
    var temp = m[1];
    var scale = m[2];
    if (scale == "C") return "$temp° C";
    assert(scale == "F");
    var fahrenheit = double.parse(temp);
    var celsius = fahrenheitToCelsius(fahrenheit);
    var dot = temp.indexOf('.');
    var decimals = dot < 0 ? 0 : temp.length - dot - 1;
    var celsiusString = celsius.toStringAsFixed(decimals);
    return "$celsiusString° C";
  });
}

double fahrenheitToCelsius(num fahrenheit) => (fahrenheit - 32) * 5 / 9;

// Example:
main() {
  var s = "ab [{50°}{F}] cd[{50.25°}{C}]..[{-12°}{F}]";
  print(convertTemperaturesToCelsius(s));
}

I chose to allow decimals on the numbers, and output with the same number of decimals as the input, and recognized both {C} and {F} as original temperatures. Your details might vary.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top