如何在Java中使用charAt()方法检查多个索引?

时间:2020-10-09 20:57:20

标签: java arrays string

我正在尝试根据char的索引比较.txt文件输入中的两个字符串数组。

So String1[i] is not complete -> example: B_nana.

String2[j] is the fitting word for string 1 -> Banana

如果程序找到匹配的索引,例如->都在索引1处有“ a”,它将检查字符串长度,如果字符串也匹配,它将替换String1[i] = String2[j].

但是每次比较时charAt()索引超过字符串的长度(一个字符串比另一个短),我得到StringOutOfBoundException

所以我的问题是,有什么办法不仅可以比较两个字符串的一个索引,还可以比较所有字符串? 我已经尝试使用

string.substring(0, str.length -1),但那根本不起作用。

感谢您的任何建议,如果您需要更多信息来回答我的问题,请随时声明。

1 个答案:

答案 0 :(得分:1)

根据您的评论,我将执行以下操作:

  1. 建立有效单词列表(列出knownWords)
  2. 建立带有空格的单词列表(列出guessWords)

这是一些伪代码

  • 对于猜测中的每个单词
    • while(!match &&在knownWords中有更多单词)
      • 将匹配项设置为false
      • 将当前猜词的长度与已知词中的第n个词进行比较
      • 如果它们的长度相同,则比较每个字符。如果已知单词中的每个字符等于猜测单词中的每个字符,或者猜测单词的字符为_,则match = true

这应该使您走上正确的轨道

示例源代码(Java)

package eu.webfarmr;

/**
 * This class takes in 2 lists (or arrays) and tries to match words from the first array to words in the second
 * the underscore (_) is considered to be a missing letter.
 * @author dbrossard
 *
 */
public class WordMatcher {
    private final static String[] knownWords = {"apple", "arcane", "batter", "butter", "banana"};
    private final static String[] guessWords = {"a___e","a____e","__tte_","b_____"};
    public static void main(String[] args) {
        for (String guessWord : guessWords) {
            boolean matchFound = false;
            int i = 0;
            while (!matchFound && i < knownWords.length) {
                if (guessWord.length()==knownWords[i].length()) {
                    int j = 0;
                    while (j < guessWord.length() && (guessWord.charAt(j)==knownWords[i].charAt(j) || guessWord.charAt(j)=='_') ) {
                        j++;
                    }
                    matchFound = (j == guessWord.length());
                    if (matchFound) {
                        System.out.println(guessWord + " matches " + knownWords[i]);
                    }
                }
                i++;
            }
        }
    }
}

如果您要查找所有匹配项,而不仅仅是将第一个匹配项从while (!matchFound && i < knownWords.length) {更改为while (i < knownWords.length) {

以下是示例输出:

a___e matches apple
a____e matches arcane
__tte_ matches batter
__tte_ matches butter
b_____ matches batter
b_____ matches butter
b_____ matches banana