As you said that the format can be varied ( min
, mins
, miNs
, etc ...) I'll post another way of doing considering spaces and not words.
You can use the Scanner
for this, the staff only remembers to read with System.in
but it has several useful resources. Scanner#next()
returns the next incoming token, and these tokens are, by default, separated by spaces.
If the input format is always the one you posted, then you can use next() + next()
to get the tokens two at a time. It would look like this:
TOKENS: 8 | hrs | 2 | mins
^ ^ ^ ^
| | | |
| | | |
CHAMADAS: next() + next() | next() + next()
^ ^
| |
RESULTADO: 8hrs | 2mins
I made a method with this logic:
public String format(String string){
Scanner scanner = new Scanner(string);
StringBuilder sb = new StringBuilder();
while(scanner.hasNext())
sb.append(scanner.next())
.append(scanner.next())
.append(" ");
return sb.toString();
}
And in the tests the results were:
String test1 = "50 min";
String test2 = "20 hrs 50 mins";
String test3 = "1 d 20 hrs 50 min";
String test4 = "3 meses 15 dias 20 horas 50 minutos";
System.out.println(format(test1)); // 50min
System.out.println(format(test2)); // 20hrs 50mins
System.out.println(format(test3)); // 1d 20hrs 50min
System.out.println(format(test4)); // 3meses 15dias 20horas 50minutos