Monday 29 November 2021

Program to determine whether two strings are the anagram

Anagram

Program to determine whether two strings are the anagram

Two Strings are called the anagram if they contain the same characters. However, the order or sequence of the characters can be different. In this program, our task is to check for two strings that, they are the anagram or not. For this purpose, we are following a simpler approach.

First of all, Compare the length of the strings, if they are not equal in the length then print the error message and make an exit, otherwise, convert the string into lower-case for the easy comparisons. Sort both the strings using bubble sort or other sorting methods. If the strings are found to be identical after sorting, then print that strings are anagram otherwise print that strings are not the anagram.

string 1

Brag

String 2

Grab

Class

Program

class Anagram {

public static void main(String[] args)

//declare array

String str1="Brag";

String str2="Grab";

//Converting both the string to lower case.

str1 = str1.toLowerCase();

str2 = str2.toLowerCase();

//Checking for the length of strings

if (str1.length() != str2.length()) {

System.out.println( "Both the strings are not anagram" );

}

else{

//Converting both the arrays to character array

char[] string1 = str1.toCharArray();

char[] string2 = str2.toCharArray();

//Sorting the arrays using in-built function sort ()

Arrays.sort(string1);
Arrays.sort(string2);

//Comparing both the arrays using in-built function equals ()

if (Arrays.equals(string1, string2) == true ) {

System.out.println( "Both the strings are anagram" );

}

else{

System.out.println( "Both the strings are not anagram" );

}

}

output

Both the strings are anagram

Theory:-

the two string are called the anagram ,so that is some word/letter in the oder of sequnce is differnt. in this program taks to find the given two strings are anagram or not anagram.for this purpose the following method are given below:-

first of all, the given strings are to convert either uppercase or lowercase .then to find length of the given string by useing length() function of string. firstly we have to check the strings are equals length then to find out the anagram string but not length are equals then show out the error of the given program.

then , first of all string are converted into array .it is easy to sorting the string(array) as basis of the our requirement .in this problem we have to use Arrays sort() method use that is to sorted the given string. and then compaire two string are the true (quals).then print that strings are anagram otherwise that string are not anagram.

No comments:

Post a Comment

How do you select data from a table in SQL?

Create Table How do you select data a table in SQL? The SELECT statement is used to se...