📜  java字符串charat

📅  最后修改于: 2020-09-26 06:01:44             🧑  作者: Mango

Java字符串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开头

Returns

字符值

Specified by

CharSequence接口,位于java.lang包内。

Throws

StringIndexOutOfBoundsException:如果index为负值或大于此字符串长度。

Java String charAt()方法示例

public class CharAtExample{
public static void main(String args[]){
String name="javatpoint";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}

输出:

t

带有charAt()的StringIndexOutOfBoundsException

让我们看一下传递更大索引值的charAt()方法的示例。在这种情况下,它将在运行时引发StringIndexOutOfBoundsException。

"public class CharAtExample{
public static void main(String args[]){
String name="javatpoint";
char ch=name.charAt(10);//returns the char value at the 10th index
System.out.println(ch);
}}

输出:

 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 10
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)

Java String charAt()示例3

让我们看一个简单的示例,在该示例中,我们从提供的字符串中访问第一个和最后一个字符。

 public class CharAtExample3 {
public static void main(String[] args) {
    String str = "Welcome to Javatpoint portal";    
    int strLength = str.length();    
    // Fetching first character
    System.out.println("Character at 0 index is: "+ str.charAt(0));    
    // The last Character is present at the string length-1 index
    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 String charAt()示例4

让我们看一个示例,其中我们访问出现在奇数索引处的所有元素。

 public class CharAtExample4 {
public static void main(String[] args) {
String str = "Welcome to Javatpoint 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 J
Char at 13 place v
Char at 15 place t
Char at 17 place o
Char at 19 place n
Char at 21 place  
Char at 23 place o
Char at 25 place t
Char at 27 place l

Java String charAt()示例5

让我们看一个示例,其中我们在计算字符串字符的频率。

 public class CharAtExample5 {
public static void main(String[] args) {
String str = "Welcome to Javatpoint 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);
}
}

输出:

 Frequency of t is: 4