简体   繁体   中英

How do I properly sort the characters of a String to compare to another String in Java?

I am very new to Java and I am currently working on a "Hidden Word" program that is able to take input from the user, 2 Strings, and see if the 2nd String is contained within the 1st. The tricky part that I have been dealing with is that the word in the 1st String does not have to be in the same order as that of the 2nd String.

For example, the word "tot" can be found in the word "tomato" even though it is not present in that exact order.

I figured out that I could sort the characters of the String to test if they could match, but whenever I try using test data, It always prints that the word could not be found from the 1st String.

If anyone could give me a hint as to what I'm missing I'd really appreciate it. I don't really get why it always prints out as no.

And as another note, I read somewhere about the BitSet util being a better option than a character array if you want to use Strings that are different lengths, but I'm not sure if that's true or if it's even sorting the characters.

public static void main(String[] args) 
{                                               
    input = new Scanner(System.in);                                                         

    System.out.println("Please enter a word");                                          //prompts user for a word
    String word = input.next();                                                         

    System.out.println("Please enter a word you would like to search");                 //prompts user again to enter a word that they would like to search for within the first word 
    String search = input.next();

    if (usedChar(word).equals(usedChar(search)))                                        //method call using the two input variables
    {                                                                                   //the if statement checks to see if the two Strings are equal
        System.out.print("The word " + search + " is found in the word " + word);
    }
    else 
    {
        System.out.print("The word was not found in " + word);                          //returns second print statement if the Strings do not match 
    }
}

public static BitSet usedChar(String s){//method to iterate through Strings 
    BitSet bs = new BitSet();
    for (int i = 0; i < s.length(); i++) {
        bs.set(s.charAt(i));
    }
    return bs;
}

Your current approach isn't working because you're checking to see if the two BitSets that represent your input strings are equal, which they won't be unless the two strings have exactly the same letters. I don't think sorting the letters in the strings will work either. You won't find the sequence "abc" in the sequence "aabbcc" even though both strings are sorted.

A better approach might be to create a HashMap from each string with each letter as the key and the number of times it occurs as the value. Then check the 1st word to make sure it has enough occurences of each letter to hide the 2nd word.

Performance can be improvable but could you try below code;

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.println("Please enter a word"); // prompts user for a word
    String word = input.next();
    char[] charOfWrds = word.toCharArray();

    System.out.println("Please enter a word you would like to search");
    String search = input.next();
    char[] charOfSrch = search.toCharArray();

    if (isContains(charOfWrds, charOfSrch)) // method call using the
    // two input variables
    { // the if statement checks to see if the two Strings are equal
        System.out.print("The word " + search + " is found in the word "
                + word);
    } else {
        System.out.print("The word was not found in " + word); 
    }

}

public static Boolean isContains(char[] charOfWrds, char[] charOfSrch) {
    int count = 0;
    for (char cha : charOfSrch) {
        for (char chaaa : charOfSrch) {
            if (cha == chaaa)
                count++;
        }
    }
    if (count == charOfSrch.length)
        return true;
    return false;
}

An optimal solution would be to maintain an array of int which stores the count of each char in the main string.Then check for each char in the test string if count exists in the countArr.If count approches 0 break through the loop.This solution optimizes complexity to O(n) instead of using nested for loops with O(n^2).

The method countChar counts the occurences of every char in the main string and the method checkChar checks if every char in the test string has enough occurences.

 import java.util.Scanner;

    public class test {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);

            System.out.println("Please enter a word"); // prompts user for a word
            String word = input.next();
            int arr[] = countChar(word);
            System.out.println("Please enter a word you would like to search");
            String search = input.next();
            if(checkChar(search, arr)==true){
                System.out.println("Word Found!!");
            }else{
                System.out.println("Word cannot be found!!");
            }
        }

        public static int[] countChar(String s) {
            int[] countArr = new int[256];
            for (int i = 0; i < s.length(); i++) {
                countArr[s.charAt(i)] = countArr[s.charAt(i)] + 1;
            }
            return countArr;
        }

        public static boolean checkChar(String s, int[] countArr) {
            for (int i = 0; i < s.length(); i++) {
                if (countArr[s.charAt(i)] == 0) {
                    return false;
                } else {
                    countArr[s.charAt(i)] = countArr[s.charAt(i)] - 1;
                }

            }
            return true;
        }
    }

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