Didart

Mirror Words

Nov 29th, 2021 (edited)
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Scanner;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6.  
  7. public class MirrorWords {
  8.     public static void main(String[] args) {
  9.         Scanner scanner = new Scanner(System.in);
  10.  
  11.         String text = scanner.nextLine();
  12.  
  13.     //    String regex = "([@#])(?<firstWord>[A-z]{3,})\\1{2}(?<secondWord>[A-z]{3,})";
  14.         String regex = "([@#])(?<firstWord>[A-z]{3,})\\1{2}(?<secondWord>[A-z]{3,})[#@]";
  15.  
  16.         List<String> mirrorWords = new ArrayList<>();
  17.  
  18.         Pattern pattern = Pattern.compile(regex);
  19.         Matcher matcher = pattern.matcher(text);
  20.  
  21.         int counter = 0;
  22.         while (matcher.find()) {
  23.             String firstWord = matcher.group("firstWord");
  24.             String secondWord = matcher.group("secondWord");
  25.             counter++;
  26.  
  27.             StringBuilder reversedWord = new StringBuilder(secondWord);
  28.             reversedWord.reverse();
  29.             if (firstWord.equals(reversedWord.toString())) {
  30.                 mirrorWords.add(firstWord + " <=> " + secondWord);
  31.             }
  32.         }
  33.         if (counter != 0) {
  34.             System.out.printf("%d word pairs found!%n", counter);
  35.         } else {
  36.             System.out.println("No word pairs found!");
  37.         }
  38.         if (counter > 0 && mirrorWords.size() > 0) {
  39.             System.out.println("The mirror words are:");
  40.             System.out.print(String.join(", ", mirrorWords));
  41.         } else {
  42.             System.out.println("No mirror words!");
  43.         }
  44.     }
  45. }
  46.  
Add Comment
Please, Sign In to add comment