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

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

  1. Java 字符串
  2. Java 中的 String Length() 方法:如何通过示例查找
  3. Java String indexOf() 方法与子字符串和示例
  4. Java String compareTo() 方法:如何与示例一起使用
  5. Java String contains() 方法 |用示例检查子字符串
  6. Java String endsWith() 方法及示例
  7. Java String replace()、replaceAll() 和 replaceFirst() 方法
  8. Java中的插入排序算法及程序示例
  9. Python String strip() 函数与示例
  10. Python 字符串长度 | len() 方法示例
  11. Python String find() 方法及示例
  12. Java 8 - 概述