Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2020
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.35 KB | None | 0 0
  1. public class SwapWords {
  2.     static Map<Integer, String> idxToSymbolMap = new HashMap<>();
  3.  
  4.     private enum Type {MAX, MIN}
  5.  
  6.     public static void main(String[] args) {
  7.         String text = "London is the capital of Great Britain, but Kiev of Ukraineasd.";
  8.         String[] words = text.split(" ");
  9.         String maxLength = getWord(words, Type.MAX);
  10.         String minLength = getWord(words, Type.MIN);
  11.         int idxOfMax = getWordIndex(words, maxLength);
  12.         int idxOfMin = getWordIndex(words, minLength);
  13.         words[idxOfMax] = minLength;
  14.         words[idxOfMin] = maxLength;
  15.         addBackSymbols(words);
  16.         System.out.println(Strings.join(words, " "));
  17.     }
  18.  
  19.  
  20.     public static String getWord(String[] array, Type type) {
  21.         deleteSymbols(array);
  22.         Comparator<String> cByLength = Comparator.comparing(String::length);
  23.         return type == Type.MAX
  24.             ? Arrays.stream(array).max(cByLength).orElse("")
  25.             : Arrays.stream(array).min(cByLength).orElse("");
  26.     }
  27.  
  28.     public static int getWordIndex(String[] array, String word) {
  29.         int idx = 0;
  30.         deleteSymbols(array);
  31.         for (int i = 0; i < array.length; i++) {
  32.             if (array[i].equals(word)) {
  33.                 idx = i;
  34.             }
  35.         }
  36.         return idx;
  37.     }
  38.  
  39.     private static void deleteSymbols(String[] array) {
  40.         for (int i = 0; i < array.length; i++) {
  41.             if (array[i].contains(".")) {
  42.                 array[i] = array[i].replace(".", "");
  43.                 idxToSymbolMap.put(i, ".");
  44.             } else if (array[i].contains("?")) {
  45.                 array[i] = array[i].replace("?", "");
  46.                 idxToSymbolMap.put(i, "?");
  47.             } else if (array[i].contains("!")) {
  48.                 array[i] = array[i].replace("!", "");
  49.                 idxToSymbolMap.put(i, "!");
  50.             } else if (array[i].contains(",")) {
  51.                 array[i] = array[i].replace(",", "");
  52.                 idxToSymbolMap.put(i, ",");
  53.             }
  54.         }
  55.     }
  56.  
  57.     private static void addBackSymbols(String[] words) {
  58.         for (int i = 0; i < words.length; i++) {
  59.             int idx = i;
  60.             idxToSymbolMap.forEach((key, value) -> {
  61.                 if (key == idx) {
  62.                     words[idx] = words[idx] + value;
  63.                 }
  64.             });
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement