Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SwapWords {
- static Map<Integer, String> idxToSymbolMap = new HashMap<>();
- private enum Type {MAX, MIN}
- public static void main(String[] args) {
- String text = "London is the capital of Great Britain, but Kiev of Ukraineasd.";
- String[] words = text.split(" ");
- String maxLength = getWord(words, Type.MAX);
- String minLength = getWord(words, Type.MIN);
- int idxOfMax = getWordIndex(words, maxLength);
- int idxOfMin = getWordIndex(words, minLength);
- words[idxOfMax] = minLength;
- words[idxOfMin] = maxLength;
- addBackSymbols(words);
- System.out.println(Strings.join(words, " "));
- }
- public static String getWord(String[] array, Type type) {
- deleteSymbols(array);
- Comparator<String> cByLength = Comparator.comparing(String::length);
- return type == Type.MAX
- ? Arrays.stream(array).max(cByLength).orElse("")
- : Arrays.stream(array).min(cByLength).orElse("");
- }
- public static int getWordIndex(String[] array, String word) {
- int idx = 0;
- deleteSymbols(array);
- for (int i = 0; i < array.length; i++) {
- if (array[i].equals(word)) {
- idx = i;
- }
- }
- return idx;
- }
- private static void deleteSymbols(String[] array) {
- for (int i = 0; i < array.length; i++) {
- if (array[i].contains(".")) {
- array[i] = array[i].replace(".", "");
- idxToSymbolMap.put(i, ".");
- } else if (array[i].contains("?")) {
- array[i] = array[i].replace("?", "");
- idxToSymbolMap.put(i, "?");
- } else if (array[i].contains("!")) {
- array[i] = array[i].replace("!", "");
- idxToSymbolMap.put(i, "!");
- } else if (array[i].contains(",")) {
- array[i] = array[i].replace(",", "");
- idxToSymbolMap.put(i, ",");
- }
- }
- }
- private static void addBackSymbols(String[] words) {
- for (int i = 0; i < words.length; i++) {
- int idx = i;
- idxToSymbolMap.forEach((key, value) -> {
- if (key == idx) {
- words[idx] = words[idx] + value;
- }
- });
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement