Thursday 9 January 2014

Java: find if two words are anagram in an array of strings




/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ques2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 *
 * @author Sunshine
 */
public class Ques2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        String AS[] = new String[]{"", "", "", "", "", ""};
        System.out.println("Enter array of strings");
        for (int i = 0; i < AS.length; i++) {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            AS[i] = br.readLine().toLowerCase();
        }
        for (int i = 0; i < AS.length; i++) {
            for (int j = i + 1; j < AS.length; j++) {
                if (AS[i].length() == AS[j].length()) {
                    char c1[] = null;
                    char c2[] = null;
                    c1 = AS[i].toCharArray();
                    c2 = AS[j].toCharArray();

                    Arrays.sort(c1);
                    Arrays.sort(c2);

                    if (Arrays.equals(c1, c2)) {
                        System.out.println("Both strings are equal and hence they have anagram at " +i+j);
                    } else {
                        System.out.println("Sorry No anagram in the strings entered");
                    }
                }
            }
        }



    }
}

No comments:

Post a Comment