亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> java

Java String.charAt() 详解:语法、返回类型、异常与实战示例

Java String.charAt() 方法是什么?

String.charAt() 返回字符串指定索引处的字符。Java 字符串索引从 0 开始,范围 0 至 length() - 1。

方法签名

public char charAt(int index)

参数

index —— 指定所需字符位置的单个 int 值。

返回值

返回给定索引处的字符(类型 char)。

异常

若 index 为负或大于等于字符串长度,抛出 StringIndexOutOfBoundsException。

实战示例

public class CharAtExample { public static void main(String[] args) { String s = "This is String CharAt Method"; // 索引 0 处字符 System.out.println("Character at 0 position is: " + s.charAt(0)); // 索引 5 处字符 System.out.println("Character at 5th position is: " + s.charAt(5)); // 索引 22 处字符 System.out.println("Character at 22nd position is: " + s.charAt(22)); // 尝试访问非法索引 char invalid = s.charAt(-1); System.out.println("Character at -1 position is: " + invalid); } } 

输出:

Character at 0 position is: T
Character at 5th position is: i
Character at 22nd position is: M

Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: -1

关键点:

java

  1. Python strip() 方法完全指南:去除首尾空白与自定义字符实战
  2. Python len() 函数实战指南:测量字符串、列表、元组、字典等对象长度
  3. Python 字符串 find() 方法完全指南:语法、参数、替代方案与计数技巧
  4. 精通 Java 字符串:创建、方法与最佳实践
  5. Java String length() 方法:获取字符串长度(示例)
  6. 精通 Java String.indexOf():定位子字符串与实战示例
  7. 精通 Java String compareTo():语法、用例与实战示例
  8. Java String.contains() 方法:检查子字符串是否存在(实战示例)
  9. 精通 Java String.endsWith():检查字符串后缀(示例)
  10. Java 字符串替换大全:replace()、replaceAll() 与 replaceFirst() 详解
  11. Java 插入排序算法详解:核心原理、完整代码与步骤演示
  12. Java 8 概览:函数式编程、流式 API 与日期时间新特性