搜索字符串是否有一个字符 [英] Searching if String differs by one character

查看:125
本文介绍了搜索字符串是否有一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to determine if a word entered differs by one character in a text file. I have code that works, but unfortunately only for words that are two characters or less which obviously isn't very useful, and the code itself looks a bit messy. Here's what I have so far:

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 是用户输入的单词,单词是要在文本文件中搜索的单词。

With random being the word that was entered by the user, and word being the word to search for in the text file.

如果我将第二个 if 语句更改为

If I changed my second if statement to something along the lines of

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

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

and if I change int i to be = 1 instead, I seem to get more of what I'm looking to accomplish, but then my code is searching for only if the first two letters are the same and not if the last two are as well, which it should be doing.

推荐答案

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

I assume you need a function like this? I just wrote and tested it.

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;
}

这篇关于搜索字符串是否有一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆