Java String charAt()方法示例
原文:https://www . geesforgeks . org/Java-string-charat-method-example/
Java String charAt() 方法返回指定索引处的字符。索引值应该介于 0 和 length()-1 之间。 签名:
public char charAt(int index)
参数:
index- Index of the character to be returned.
返回:
returns character at the specified position.
例外:
StringIndexOutOfBoundsException- If index is
negative or greater then the length of the
String.
示例:展示 charAt() 方法的工作
// Java program to demonstrate
// working of charAt() method
class Gfg {
public static void main(String args[])
{
String s = "Welcome! to Geeksforgeeks Planet";
char ch = s.charAt(3);
System.out.println(ch);
ch = s.charAt(0);
System.out.println(ch);
}
}
Output:
c
W
// Java program to demonstrate
// working of charAt() method
class Gfg {
public static void main(String args[])
{
String s = "abc";
char ch = s.charAt(4);
System.out.println(ch);
}
}
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at Gfg.main(File.java:9)
版权属于:月萌API www.moonapi.com,转载请注明出处