搜索字符串是否有一个字符

我正在尝试确定输入的单词是否因文本文件中的一个字符而异。 我有适用的代码,但不幸的是只有两个字符或更少的字,显然不是很有用,代码本身看起来有点乱。 这是我到目前为止所拥有的:

if(random.length() == word.length()){ for(int i = 0; i < random.length(); i++){ if( (word.charAt(i) == random.charAt(i))){ str += word+"\n"; count++; } } } 

random是用户输入的单词, word是在文本文件中搜索的单词。

如果我将第二个if语句更改为某些内容

 if( (word.charAt(i) == random.charAt(i)) && (word.charAt(i -1) == random.charAt(i-1))) 

如果我改变int i为= 1,我似乎得到了更多我想要完成的东西,但是我的代码只搜索前两个字母是否相同而不是如果最后两个字母是好吧,应该做的。

我假设你需要这样的function? 我刚刚编写并测试了它。

 static boolean equals(String word1, String word2, int mistakesAllowed) { if(word1.equals(word2)) // if word1 equals word2, we can always return true return true; if(word1.length() == word2.length()) { // if word1 is as long as word 2 for(int i = 0; i < word1.length(); i++) { // go from first to last character index the words if(word1.charAt(i) != word2.charAt(i)) { // if this character from word 1 does not equal the character from word 2 mistakesAllowed--; // reduce one mistake allowed if(mistakesAllowed < 0) { // and if you have more mistakes than allowed return false; // return false } } } } return true; } 

您的代码似乎对我有用,您可能会错误地解释其结果。

这可能更明显:

 int count = 0; if(random.length() == word.length()) { for(int i = 0; i < random.length(); i++) { if( (word.charAt(i) != random.charAt(i) )) { if(count == 0) { System.out.println("Found first difference!"); } if(count != 0) { System.out.println("Strings are more than one letter different!"); } count++; } } } 

如果要检查不同长度的字符串,则需要从较长的字符中删除字符,直到它与较短的字符串相同。 例如:如果String1 =“abc”; 和String2 =“zzzabcdef”;

您需要从第二个字符串中删除6个字符,并测试删除的6个字符的每个组合。 所以你想测试字符串:def,cde,abc,zab,zza,zzz,zzb,zzc,zzd,zze,zzf,zaf,zae,zad,zac,zab,zza,zzf,zze,... ,...,等等,列表大小为9选6,所以它绝对不是最佳或推荐的。

但是,您可以检查一个字符长于另一个字符的字符串是否只是另一个添加了字母的字符串。 要做到这一点,你想要一个for循环从0到i,从i + 1到结尾抓取两个子串。 这将省略第i个字符,并循环字符串的大小 - 1将首先给出完整的字符串,然后是没有第一个字母的字符串,然后缺少第二个字母,依此类推。 然后以与上面相同的方式测试子字符串。

如果这不是您正在寻找的评论。

编辑

要查看文件中有多少单词是一个与变量单词不同的单词,您需要遍历文件,获取每个单词。 然后测试是否是字符串是一个字母关闭。 它会是这样的:

 String testAgainst = "lookingForWordsOneLetterDifferentThanThisString"; int words = 0; Scanner scan = new Scanner(fileName); while(scan.hasNext()) { String word = scan.next(); if( isOneDifferent(word, testAgainst) ) { words++; } System.out.println("Number of words one letter different: " + words); } public boolean isOneDifferent(String word, String testAgainst) { if(word.length() != testAgainst.length()) { return false; } int diffs = 0; for(int i = 0; i < word.length(); i++) { if(word.charAt(i) != testAgainst.charAt(i)) { diffs++; } if(diffs > 1) { return false; } } if(diffs == 1) { return true; } else { return false; } }