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);
}
}
輸出:
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);
}
}
輸出:
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)
相關用法
- Java StringBuilder charAt()用法及代碼示例
- Java CharBuffer charAt()用法及代碼示例
- Java Collator compare(String, String)用法及代碼示例
- Java Collator equals(String, String)用法及代碼示例
- Java Java.lang.string.replace()用法及代碼示例
- Java String contains()用法及代碼示例
- Java String trim()用法及代碼示例
- Java String isEmpty()用法及代碼示例
- Java ZoneOffset of(String)用法及代碼示例
- Java String toString()用法及代碼示例
- Java String subSequence()用法及代碼示例
- Java Java.lang.String.lastIndexOf()用法及代碼示例
- Java RuleBasedCollator getCollationElementIterator(String)用法及代碼示例
- Java CollationElementIterator setText(String)用法及代碼示例
注:本文由純淨天空篩選整理自Niraj_Pandey大神的英文原創作品 Java String charAt() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。