在字符数组中为字符串分配区域时,字符串的大小会增加



我一直很难弄清楚String stringMatch大小增加的原因。由于它的大小增加,所以它超出了界限。我一直在对一个文本文件进行线性搜索,找到一个与用户输入的内容相匹配的单词。有人看到我用这个代码做错了什么吗?

input = new Scanner(System.in);

System.out.print("Please enter a word to be searched or type EINPUT to quit: ");
String userString = input.next();
while(!userString.equals("EINPUT")) {
boolean bool = false;
if(userString.equals("EINPUT")) {
System.exit(1);
}
char[] charSearch = userString.toCharArray();
for(int i = 0; i < text.length; i++) {
for (int k = 0; k < (text[i].length - charSearch.length); k++) {
String stringMatch = new String(text[i], k, k + charSearch.length);
if(stringMatch.equals(userString)) {
System.out.printf("Line number %d", i + 1);
bool = true;
}
}

}
if (bool == false) {
System.out.printf("The word %s is not in the text file", userString);
}
System.out.print("Please enter a word to be searched or type EINPUT to quit: ");
userString = input.next();
}

我正在测试的文本文档很短。如下所示:

这是一个阳光明媚的日子

在虚构的土地上

这是输出

It w
t was
was a
was a b
as a bea
s a beaut
a beautif
a beautiful
beautiful s
beautiful sun
eautiful sunny
autiful sunny d
utiful sunny day

当它到达第一行的末尾后,我得到了一个ArrayIndexOutOfBoundsException

String stringMatch = new String(text[i], k, k + charSearch.length);

这条线就是问题所在。第三个参数应该是新字符串的长度,而不是结束索引。因此,您需要从k + charSearch.length更改为charSearch.length,然后它应该可以工作。

最新更新