As you said the format can be varied ( min
, mins
, miNs
, etc...) I will post another way of doing considering the spaces and not the words.
You can use the class Scanner
for this, the staff only remembers her to do reading with System.in
but it has several useful resources. Scanner#next()
returns the next input 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 pick up the tokens two by two. 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
You said you don’t know which sequences "hrs", "mins" come in the string. And which ones can come, you know? If you know, just call
replace()
for each one that will work smoothly. Otherwise, see my solution with regex.– Piovezan
Managed to resolve @dnsfirmino?
– durtto