简体   繁体   中英

Wrapping a switch statement in a neat loop in Java

I have the following code that takes 2 strings as inputs and returns Boolean on whether they're anagrams:

import java.util.ArrayList;
import java.util.Scanner;

public class AnagramChecker {

    public static void main(String[] args) {
        Scanner sc = new Scanner (System.in);
        System.out.print ("Enter string 1: ");
        String str1 = sc.nextLine();
        System.out.print ("Enter string 2: ");
        String str2 = sc.nextLine();

        boolean check = isAnagram (str1, str2);
        System.out.println ("Anagram check for '" + str1 + "' and '" + str2 + "': " + check);
        sc.close();
    }
    public static boolean isAnagram (String s1, String s2) {
        if(s1.length() != s2.length())
            return false;
        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();
        ArrayList<String> myList = new ArrayList<String>();
        for(int i = 0; i < s2.length() ; i++ ){
            myList.add(String.valueOf(s2.charAt(i)));
        }
        for(int i = 0; i < s1.length();i++){
            for(int j = 0; j < myList.size(); j++){
                if(myList.get(j).equals(String.valueOf(s1.charAt(i)))){

                        myList.remove(j);
                        j = 0;
                        break;
                }
            }
        }
        return myList.isEmpty();
    }
}

It is somewhat limited though, I'm trying to expand it to work for the following cases: - different cases ie eager == AGREE - single word with whitespaces ie eager == ag ree - different amounts of whitespace ie " eager" == agree

Is there a nice and clean way to integrate this into already written code above without much pain and re-writing. Any help much appreciated. Thanks.

Yes there is. Regex to the rescue! You can use the String built in .replaceAll(). Passing it the \\s value will remove all spaces and characters not printed such as \\n. I would suggest that during comparison you use something like the following:

string1.replaceAll("\\s","").equals(string2.replaceAll("\\s",""));

personally I would do the following

  • use trim() to remove leading and traiing whitespace
  • use replace to remove whitespaces
  • use toLowerCase () to make the text lower case
  • convert the Strings into an array list of characters
  • sort the arrays
  • compare the arrays - if they are the same then you have an anagram

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM