The problem
Your job is to kind a given string. Every phrase within the string will include a single quantity. This quantity is the place the phrase ought to have within the outcome.
Observe: Numbers might be from 1 to 9. So 1 would be the first phrase (not 0).
If the enter string is empty, return an empty string. The phrases within the enter String will solely include legitimate consecutive numbers.
Examples
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
"" --> ""
The answer in Java code
Possibility 1:
public class Order {
public static String order(String phrases) {
String[] _words = phrases.cut up(" ");
String[] out = new String[_words.length];
for (int i=0; i<_words.size; i++) {
for (Character c : _words[i].toCharArray()) {
if (Character.isDigit(c)) {
out[Character.getNumericValue(c)-1] = _words[i];
}
}
}
if (out.size<=1) return "";
return java.util.Arrays.stream(out).gather(java.util.stream.Collectors.becoming a member of(" "));
}
}
Possibility 2:
import java.util.Arrays;
import java.util.Comparator;
public class Order {
public static String order(String phrases) {
return Arrays.stream(phrases.cut up(" "))
.sorted(Comparator.evaluating(s -> Integer.valueOf(s.replaceAll("D", ""))))
.scale back((a, b) -> a + " " + b).get();
}
}
Possibility 3:
public class Order {
public static String order(String phrases) {
String[] arr = phrases.cut up(" ");
StringBuilder outcome = new StringBuilder("");
for (int i = 0; i < 10; i++) {
for (String s : arr) {
if (s.comprises(String.valueOf(i))) {
outcome.append(s + " ");
}
}
}
return outcome.toString().trim();
}
}
Take a look at circumstances to validate our answer
import static org.junit.Assert.*;
import org.junit.Take a look at;
import static org.hamcrest.CoreMatchers.*;
public class OrderTest {
@Take a look at
public void test1() {
assertThat(Order.order("is2 Thi1s T4est 3a"), equalTo("Thi1s is2 3a T4est"));
}
@Take a look at
public void test2() {
assertThat(Order.order("4of Fo1r pe6ople g3ood th5e the2"), equalTo("Fo1r the2 g3ood 4of th5e pe6ople"));
}
@Take a look at
public void test3() {
assertThat("Empty enter ought to return empty string", Order.order(""), equalTo(""));
}
}