Java >> Tutoriel Java >  >> Java

Exemple de programme Java d'anagramme

Qu'est-ce qu'une anagramme ?

Deux ensembles d'une chaîne sont dits anagrammes s'ils contiennent exactement les mêmes caractères mais dans un ordre différent.

par exemple :

Silencieux et Écoutez sont des anagrammes l'un de l'autre car les deux ont le même jeu de caractères mais dans un ordre différent.

Quelque autre exemple d'anagramme

Les yeux Ils voient
Funérailles Vraiment amusant
Un gentleman Homme élégant

Dans ce didacticiel, vous apprendrez à écrire un programme Java pour vérifier si un ensemble de chaînes est anagramme ou non.

//Java program to find two strings are anagram or not

//Importing util library with all package
import java.util.*;

//Main / Drived Class
public class Main{

  //main function of the program
  public static void main (String[] args) {
    //Creating object of Scanner Class
    Scanner input = new Scanner(System.in);
    //Printing message what to enter to help user
    System.out.print("Enter first string : ");
    //taking first string input
    String str1 = input.nextLine();
    //Printing message what to enter to help user
    System.out.print("Enter second string : ");
    //taking second string input
    String str2 = input.nextLine();

    // replace all spaces from targeted string
    str1 = str1.replaceAll("\\s","");
    // replace all spaces from targeted string
    str2 = str2.replaceAll("\\s","");

    //Create a boolean type variable with true value
    boolean status = true;
    //Checking the length of both strings
    //If length of doesn't match it can't be anagram
    if(str1.length() != str2.length()){
      //If string 1 and string 2 length not equals change status value
      status = false;
    }else{
      //f string 1 and string 2 length equals to each other
      //Converting strings into characters array
      char[] char1 = str1.toLowerCase().toCharArray();
      //Converting strings into characters array
      char[] char2 = str2.toLowerCase().toCharArray();
      //Sorting array of characters
      Arrays.sort(char1);
      //Sorting array of characters
      Arrays.sort(char2);
      //checking the equality of both Arrays
      status = Arrays.equals(char1, char2);
    }
    //Checking the status value
    if(status){
      //If status value is true
      System.out.println("STRINGS ARE ANAGRAMS");
    }else{
      //If status value is false
      System.out.println("STRINGS ARE NOT ANAGRAMS");
    }

  }
} 

Sortie

Enter first string: funeral
Enter second string: real fun
STRINGS ARE ANAGRAMS


Balise Java