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

use*_*708 5 java for-loop if-statement

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

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

随着random被认为是由用户输入的单词,然后word是搜索文本文件中的单词.

如果我将我的第二个if陈述改为某些内容

if( (word.charAt(i) == random.charAt(i)) && (word.charAt(i -1) == random.charAt(i-1)))
Run Code Online (Sandbox Code Playgroud)

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

luu*_*sen 8

我假设你需要这样的功能?我刚刚编写并测试了它.

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;
}
Run Code Online (Sandbox Code Playgroud)