Java String charAt() 方法及示例
什么是Java String charAt() 方法?
Java 字符串 charAt() 方法从字符串返回确定索引处的字符。在这个Java方法中,字符串索引值从0开始,一直到字符串长度减1(n-1)。
charAt() 方法语法
public char charAt(int index)
charAt() 方法的参数输入
索引 – 此 Java 方法仅接受 int 数据类型的单个输入。
Java String charAt() 方法的返回类型
Java String charAt() 方法根据索引输入返回一个字符类型数据。
异常
如果索引值不在 0 和字符串长度减一之间,则抛出 java.lang.StringIndexOutOfBoundsException
Java String charAt() 方法示例
public class CharAtGuru99 { public static void main(String args[]) { String s1 = "This is String CharAt Method"; //returns the char value at the 0 index System.out.println("Character at 0 position is: " + s1.charAt(0)); //returns the char value at the 5th index System.out.println("Character at 5th position is: " + s1.charAt(5)); //returns the char value at the 22nd index System.out.println("Character at 22nd position is: " + s1.charAt(22)); //returns the char value at the 23th index char result = s1.charAt(-1); System.out.println("Character at 23th position is: " + result); } }
输出:
第0位的字符是:T
第5位的字符是:i
第22位的字符是:M
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:-1
关于 Java charAt() 方法的一些重要事项:
- 此 Java 方法接受一个始终为 int 类型的参数。
- 此方法将字符作为给定 int 参数的字符返回。 int 值指定从 0 开始的索引。
- 如果索引值大于字符串长度或为负数,则发生 IndexOutOfBounds Exception 错误。
- 索引范围必须在 0 到 string_length-1 之间。
java
- Java 字符串
- Java 中的 String Length() 方法:如何通过示例查找
- Java String indexOf() 方法与子字符串和示例
- Java String compareTo() 方法:如何与示例一起使用
- Java String contains() 方法 |用示例检查子字符串
- Java String endsWith() 方法及示例
- Java String replace()、replaceAll() 和 replaceFirst() 方法
- Java中的插入排序算法及程序示例
- Python String strip() 函数与示例
- Python 字符串长度 | len() 方法示例
- Python String find() 方法及示例
- Java 8 - 概述