我對Java很新,我目前正在研究一個能夠從用戶輸入2個字符串並查看第二個字符串是否包含在第一個字符串中的「隱藏字」程序。我一直在處理的棘手部分是第一個字符串中的單詞不必與第二個字符串的順序相同。如何正確排序字符串的字符以與Java中的另一個字符串進行比較?
例如,單詞「TOT」可以在單詞「番茄」,即使它不存在在確切順序找到。
我想通了,我可以在字符串中的字符進行排序,以測試他們是否能匹配,但每當我嘗試使用測試數據,它總是打印出的文字無法從1弦被發現。
如果任何人都可以給我一個提示,我很想念我會很感激。我真的不明白爲什麼它總是打印出不是。
作爲另一個說明,如果您想使用不同長度的字符串,我會在BitSet util的某個位置讀取比字符數組更好的選項,但我不確定這是否爲真,或者它甚至將它排序字符。
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;
}
感謝您的幫助。我測試了代碼,它適用於連續的字符。當我使用上面提到的測試數據時,單詞「tot」在單詞「tomato」中仍然無法識別,我會嘗試着解決這個問題。感謝您的幫助,如果您有任何想法或資源我可以查看,以便我可以解決這個問題,我會很感激。 – Albert 2014-12-04 21:13:44