Java String charAt()
java字符串charAt()方法在给定的索引号处返回
char值 。
索引号从0开始到n-1,其中n是字符串的长度。如果给定的索引号大于或等于此字符串长度或负数,则返回
StringIndexOutOfBoundsException 。
内部实现
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
签名
字符串charAt()方法的签名如下:
public char charAt(int index)
参数
index: 索引号,以0开头
返回
字符值
由
CharSequence 接口指定,位于java.lang包内。
抛出
StringIndexOutOfBoundsException : 如果index为负值或大于此字符串长度。
Java字符串charAt()方法示例
public class CharAtExample{
public static void main(String args[]){
String name="lidihuo";
char ch=name.charAt(4);
System.out.println(ch);
}
}
输出:
带有charAt()的StringIndexOutOfBoundsException
让我们看一下charAt()方法的示例,在该示例中我们传递了更大的索引值。在这种情况下,它将在运行时引发StringIndexOutOfBoundsException。
public class CharAtExample{
public static void main(String args[]){
String name="lidihuo";
char ch=name.charAt(10);
System.out.println(ch);
}
}
输出:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10at java.lang.String.charAt(String.java:658)at CharAtExample.main(CharAtExample.java:4)
Java字符串charAt()示例3
让我们看一个简单的示例,我们从提供的字符串中访问第一个和最后一个字符。
public class CharAtExample3 {
public static void main(String[] args) {
String str = "Welcome to lidihuo portal";
int strLength = str.length();
System.out.println("Character at 0 index is: "+ str.charAt(0));
System.out.println("Character at last index is: "+ str.charAt(strLength-1));
}
}
输出:
Character at 0 index is: W
Character at last index is: l
Java字符串charAt()示例4
让我们看一个示例,其中我们访问出现在奇数索引处的所有元素。
public class CharAtExample4 {
public static void main(String[] args) {
String str = "Welcome to lidihuo portal";
for (int i=0; i<=str.length()-1; i++) {
if(i%2!=0) {
System.out.println("Char at "+i+" place "+str.charAt(i));
}
}
}
}
输出:
Char at 1 place e
Char at 3 place c
Char at 5 place m
Char at 7 place
Char at 9 place o
Char at 11 place l
Char at 13 place d
Char at 15 place h
Char at 17 place o
Char at 19 place p
Char at 21 place r
Char at 23 place a
Java字符串charAt()示例5
让我们看一个示例,其中我们计算字符串中字符的频率。
public class CharAtExample5 {
public static void main(String[] args) {
String str = "Welcome to lidihuo portal";
int count = 0;
for (int i=0; i<=str.length()-1; i++) {
if(str.charAt(i) == 't') {
count++;
}
}
System.out.println("Frequency of t is: "+count);
}
}
输出: