我正在尝试根据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)
,但那根本不起作用。
感谢您的任何建议,如果您需要更多信息来回答我的问题,请随时声明。
答案 0 :(得分:1)
根据您的评论,我将执行以下操作:
这是一些伪代码
这应该使您走上正确的轨道
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