I am trying to divide a string in flutter into text and numbers.
The string consists of a number and a measurement in the metric system. My goal is to separate the number from the measure in order to process them separately
This is information in g (gram) kg (kilogram) l (litre) and ml (millilitre) and potentially more.
the output of the method should have values that are given in grams and millilitres only. The others should be calculated down to these. How can I easily implement this in dart, as an endless if query seems wrong to me.
Example values:
"22g"=> ["22","g"] |"150 g"=> ["150","g"] |"120ml"=> ["120","ml"] |"2 l" => ["2000","ml"] |"1kg" => ["1000","g"]
My current way is like this:
List<String> splitString(String input) {
input = input.replaceAll(" ", "");
if (input.contains("ml")) {
String number = input.replaceAll("ml", "");
return [number, "ml"];
} else if(input.contains("g")){
String number = input.replaceAll("g", "");
return [number, "g"];
} else if(input.contains("kg")){
String number = input.replaceAll("kg", "");
double value = double.parse(number) * 1000;
return [value.toStringAsFixed(2), "g"];
} else{
String number = input.replaceAll("l", "");
double value = double.parse(number) * 1000;
return [value.toStringAsFixed(2), "ml"];
}
}
2
Answers
Try this!
This code takes a string input, such as ’22g’, and splits it into its numeric and alphabetic parts. It utilizes a regular expression to identify the pattern of one or more digits followed by one or more alphabetic characters. If the input matches this pattern, it returns a list containing the numeric and alphabetic parts; otherwise, it returns an empty list. Finally, the result is printed.
If you have any problem, feel free to ask me.
it’s old school, try, but it’s preferable for strings that contains empty space between numbers and chars eg: 120 l not 120l