Java学习笔记23:Java中charAt()方法的使用

此方法返回位于字符串的指定索引处的字符。该字符串的索引从零开始。

charAt(int index)方法是一个能够用来检索特定索引下的字符的String实例的方法.

charAt()方法返回指定索引位置的char值。

索引范围为0~length()-1.

如: str.charAt(0)检索str中的第一个字符符,str.charAt(str.length()-1)检索最后一个字符.

package com.xumingjie.s;
public class Cartat {
 public static void main(String[] args) {
 
   String str = "This is yiibai";
                  
   // prints character at 1st location
   System.out.println(str.charAt(0));
         
   // prints character at 5th location i.e white-space character
   System.out.println(str.charAt(4));
         
   // prints character at 18th location 
   System.out.println(str.charAt(6));
 }
}

结果如下:
T
s

String类中的IndexOf和CharAt的区别

int indexOf(int ch)
返回指定字符在此字符串中第一次出现处的索引。
int indexOf(int ch, int fromIndex)
返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
int indexOf(String str)
返回指定子字符串在此字符串中第一次出现处的索引。
int indexOf(String str, int fromIndex)
返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
通过JDK可以看出来,indexOf的参数是你要找的字符,而返回值是该字符第一次出现的索引
char charAt(int index)
返回指定索引处的 char 值。charAt方法,参数是指定的索引,返回的是该索引处的char值。把String转化成数组,显然要用的是toCharArray方法和charAt方法

猜你喜欢

转载自blog.csdn.net/qq_30242987/article/details/85774800
今日推荐