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



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

So String1[i] is not complete -> example: B_nana.
String2[j] is the fitting word for string 1 -> Banana

如果程序找到匹配的索引,例如->两者都具有";a";在索引1处,它检查字符串长度,如果匹配,则替换String1[i] = String2[j].

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

所以我的问题是,有没有办法不仅比较两个字符串的一个索引,而且比较所有字符串?我已经试过使用

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

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

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

  1. 建立有效单词列表(列出已知单词(
  2. 建立一个有间隙的单词列表(列出留言单词(

这里有一些伪代码

  • 对于留言中的每个单词单词:
    • while(!match&在knownWords中有更多单词(
      • 将match设置为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

最新更新