gpt4 book ai didi

java - 如何查找字符串中连续双字母(大写字母)的数量?

转载 作者:太空宇宙 更新时间:2023-11-04 09:38:17 27 4
gpt4 key购买 nike

我必须找到字符串中连续大写字母的数量。例如“小兔子”连续大写字母的数量 = 2(第一个是 TT,第二个是 BB)程序无法运行。

程序给出如下错误消息

java.lang.StringIndexOutOfBoundsException: String index out of range: 14

try {
String s = " LITTLE RABBIT";
s.toUpperCase();
int l = s.length();
int a = 0;
char ch1, ch2;
for (int i = 0; i < l; i++) {
ch1 = s.charAt(i);
ch2 = s.charAt(i + 1);
if (ch1 == ch2) {
a++;
}
}
System.out.println(a);
} catch (StringIndexOutOfBoundsException e) {
System.out.println(e);
}

最佳答案

尝试使用下面的代码。你必须从 0 遍历到 String Size - 1。但是你正在遍历最后一个不存在元素的位置。这就是为什么您会收到 StringIndexOutOfBounds 异常。

public static void main(String[] args) {
try {
String s = " LITTLE RABBIT";
s.trim().toUpperCase();
int l = (s.length() - 1);
int a = 0;
char ch1, ch2;
for (int i = 0; i < l; i++) {
ch1 = s.charAt(i);
ch2 = s.charAt(i + 1);
if (ch1 == ch2) {
a++;
}
}
System.out.println(a);
} catch (StringIndexOutOfBoundsException e) {
e.printStackTrace();
}

}

关于java - 如何查找字符串中连续双字母(大写字母)的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56236695/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com