我有一个字符串"1 hour 1 min"
,我需要读61分钟。我该怎么办?
答案 0 :(得分:1)
假设您一直在转换指定的格式,即xxx hour xxx min
您可以拆分字符串或使用正则表达式获取hour
和min
组件。
这是一个样本
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ConvertTimeStringSample {
public static int convertHourAndMinToMinutes(String toConvert) {
// Parse the string matching the pattern
Matcher matcher = Pattern.compile("(.*?) hour (.*?) min").matcher(toConvert);
if(matcher.find()) {
int hoursInMinutes = new Integer(matcher.group(1)) * 60; // The hours part of the string converted to an integer and multiplied into minutes
int minutes = new Integer(matcher.group(2)); // The minutes part of the string converted to an integer
int totalMinutes = hoursInMinutes + minutes; // The sum of the two, making up the total minutes
return totalMinutes;
}
throw new IllegalArgumentException("Unable to parse input string.");
}
public static void main(String[] args) throws IllegalArgumentException {
String toConvert = "1 hour 1 min";
int minutes = convertHourAndMinToMinutes(toConvert); // Call our conversion function
System.out.println("Total in minutes: " + minutes); // Display the result
}
}
输出:
Total in minutes: 61