使用。length()和。length()-1来查找字母在字符串中出现的次数有什么区别?
的例子:
for (int i = 0; i < str.length(); i++)
{
if (str.substring(i, i + 1).equals("e"))
{
count++;
}
}
System.out.println(count);
和
for (int i = 0; i < str.length() - 1; i++)
{
if (str.substring(i, i + 2).equals("th"))
{
count++;
}
}
System.out.println(count);
为什么不能同时使用str.length()呢?
因为在第二个示例中,与第一个示例一样,您使用了包含2个字符而不是1个字符的子字符串。因此,通过让for循环只运行到length - 1,循环中的最后一次迭代从字符串中获取索引长度为- 1的字符和长度为length的字符。如果在for循环中检查长度,则最后一次迭代中的子字符串将取位置为length和length + 1的字符,这显然是行不通的。
您可以创建一个适用于所有子字符串的函数。它看起来像:
int countSubstrings(String str, String s) {
int count = 0;
for (int i = 0; i < str.length() - s.length() + 1; i++)
{
if (str.substring(i, i + s.length()).equals(s))
{
count++;
}
}
return count;
}
当检查的子字符串变长时,需要提前停止遍历字符串。
(注意:上面的方法可以更有效地实现-使用String.regionMatches
-但它是为了说明你的问题)
不幸的是,在这种情况下:
count = 0;
for ( int i = 0; i < str.length(); i++) {
if (str.substring(i, i + 2).equals("th")) {
count++;
}
}
System.out.println(count);
您将得到以下异常:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 4, e
nd 6, length 5
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3756)
at java.base/java.lang.String.substring(String.java:1902)
at stackOverflow.Pattern.main(Pattern.java:22)
因为i+2
会检查字符串的i+1
位置,而这超出了字符串的长度。
如果您要使用str.length()
作为第二个,当它达到最高的i
值时,当它做子字符串i+2
将离开str
的末尾