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

标签 java string

我必须找到字符串中连续大写字母的数量。 例如“小兔子” 连续大写字母的数量 = 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/

相关文章:

Java 正则表达式 - 将 "x^2"替换为 "x²"但不是将 "x^27"替换为 "x²7"

java - 安全性:限制第三方软件的内部访问

javascript - 如果 'Ö' > ('Z' ,为什么 'Ö' .localeCompare 'Z' ) 等于 -1 而不是 1 ?

java - 字符串数组到多个对象

c# - 级联一个 url 字符串

java - 数组 - 输出必须是一年中的月份

java - Eclipse STS 4错误: Could not find or load main class

java - 如何使用来自 firebase 的嵌套对象填充 RecyclerView

c - 使用gets函数在数组中输入字符串

javascript - 在 JavaScript 中结束