Java 字符串如何查看指定字符出现的下标

在 Java 中,我们可以使用 indexOf 方法来查看指定字符在字符串中第一次出现的下标,或者使用 lastIndexOf 方法来查看指定字符在字符串中最后一次出现的下标。这两个方法返回的是一个整数值,表示指定字符在字符串中的位置。如果指定字符不存在于字符串中,则返回 -1。

下面是具体的代码示例:

public class Main {
    public static void main(String[] args) {
        String str = "Hello, World!";
        char ch = 'o';

        int firstIndex = str.indexOf(ch);
        int lastIndex = str.lastIndexOf(ch);

        System.out.println("First index of '" + ch + "' in the string: " + firstIndex);
        System.out.println("Last index of '" + ch + "' in the string: " + lastIndex);
    }
}

以上代码中,我们定义了一个字符串 str,并指定了一个字符 ch。然后,我们使用 indexOf 方法和 lastIndexOf 方法来查找字符 ch 在字符串 str 中的位置。最后,我们将结果输出到控制台。

运行以上代码,输出结果如下:

First index of 'o' in the string: 4
Last index of 'o' in the string: 8

从结果可以看出,字符 'o' 第一次出现在索引位置 4 处,最后一次出现在索引位置 8 处。

除了 indexOf 方法和 lastIndexOf 方法,我们还可以使用 charAt 方法来逐个检查字符串的每个字符,并判断是否与指定字符相等。以下是使用 charAt 方法实现的代码示例:

public class Main {
    public static void main(String[] args) {
        String str = "Hello, World!";
        char ch = 'o';

        int index = -1;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ch) {
                index = i;
                break;
            }
        }

        System.out.println("Index of '" + ch + "' in the string: " + index);
    }
}

以上代码中,我们使用一个循环遍历字符串的每个字符,通过比较字符是否相等来确定指定字符的位置。如果找到了指定字符,则将索引位置赋值给 index 变量,并使用 break 语句跳出循环。如果循环结束后 index 仍然为 -1,则表示字符串中不存在指定字符。

运行以上代码,输出结果与之前相同。

以上就是在 Java 中查看指定字符在字符串中出现的下标的方法。根据实际需求,可以选择使用 indexOf 方法、lastIndexOf 方法或 charAt 方法来实现。