Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2020
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.87 KB | None | 0 0
  1. public class SwapWords {
  2.     public static void main(String[] args) {
  3.         String text = "London is the capital of Great Britain";
  4.         String[] words = text.split(" ");
  5.         String maxLength = Arrays.stream(words).max(Comparator.comparing(String::length)).get();
  6.         String minLength = Arrays.stream(words).min(Comparator.comparing(String::length)).get();
  7.         int idxOfMax = getWordIndex(words, maxLength);
  8.         int idxOfMin = getWordIndex(words, minLength);
  9.         words[idxOfMax] = minLength;
  10.         words[idxOfMin] = maxLength;
  11.         System.out.println(Strings.join(words, " "));
  12.     }
  13.  
  14.     public static int getWordIndex(String[] array, String word) {
  15.         int idx = 0;
  16.         for (int i = 0; i < array.length; i++) {
  17.             if (array[i].equals(word)) {
  18.                 idx = i;
  19.             }
  20.         }
  21.         return idx;
  22.     }
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement