Thursday, July 19, 2018
Sunday, July 15, 2018
Given Strings are anagrams or not using java
What is String Anagram?
"An anagram is a type of word, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once.
for Example: 'java' can be rearranged as - 'vaaj' or 'vjaa' -all characters are equal in both the words. So this is called string anagram.
Now we will see how to write a java program to check whether given strings are anagram or not.
package com.siva;
import java.util.Arrays;
public class StringAnagramTest {
public boolean isStringAnagram(String s1, String s2){
char[] charArray1 = s1.toCharArray();
char[] charArray2 = s2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
boolean stringAnagram = Arrays.equals(charArray1, charArray2);
return stringAnagram;
}
public static void main(String[] args) {
StringAnagramTest test = new StringAnagramTest();
String str1 ="test";
String str2 ="sett";
boolean stringAnagram = test.isStringAnagram(str1, str2);
if(stringAnagram){
System.out.println("Given Strings["+str1+"] and ["+str2 +"] are anagrams");
}else{
System.out.println("Given Strings["+str1+"] and ["+str2 +"] are not anagrams");
}
}
}
We can provide any value as input for both the strings.
Detailed Explanation:
Step 1: Convert given Strings into character array.
Step 2: Sort the converted character array using Arrays.sort
Step 3: compare both the strings using Arrays.equals
There are different ways to implement the same logic by writing our own sorting and equals methods. this is simple way to find the result.
output:
Given Strings[test] and [sett] are anagrams
Saturday, June 9, 2018
Thursday, March 1, 2018
Java Program to check whether given word is Palindrome or not
This post will explain us, how to implement palindrome logic with different ways, using java.
public class WordPalindrome {
public static void main(String[] args) {
String word="LIRIL";
boolean isPalin = isPalindromeOne(word);
if(isPalin){
System.out.println("Given word ["+word+"] is palindrome");
}else{
System.out.println("Given word ["+word+"] is not palindrome");
}
word = "Hello";
isPalin = isPalindromeOne(word);
if(isPalin){
System.out.println("Given word ["+word+"] is palindrome");
}else{
System.out.println("Given word ["+word+"] is not palindrome");
}
}
public static boolean isPalindromeOne(String word){
boolean isPalindrome = false;
//first way of checking
char[] array = word.toCharArray();
char[] newArray = new char[array.length];
for (int i = 0; i < array.length; i++) {
char c = array[array.length-i-1];
newArray[i] =(char)c;
}
if(word.equalsIgnoreCase(String.valueOf(newArray))){
isPalindrome = true;
}
//second way of checking
String reverse ="";
for (int i = 0; i < word.length(); i++) {
char c= word.charAt(i);
reverse = c+reverse;
}
if(reverse.equalsIgnoreCase(word)){
isPalindrome = true;
}
return isPalindrome;
}
}
Subscribe to:
Posts (Atom)