String类的获取功能:
int length()
char charAt(int index)
int indexOf(int ch)
int indexOf(String str)
int indexOf(int ch,int fromIndex)
int indexOf(String str,int fromIndex)
String substring(int start)
String substring(int start,int end)
重点
int length()
String substring(int start)
String substring(int start,int end)
public class StringDemo7 {
public static void main(String[] args) {
String s = "helloworld";
//int length() 获取字符串的长度
System.out.println(s.length());
System.out.println("***************************");
//public char charAt(int index)返回char指定索引处的值
//从0开始到length()-1
System.out.println(s.charAt(7));
System.out.println(s.charAt(0));
// System.out.println(s.charAt(11));//StringIndexOutOfBoundsException
System.out.println("***************************");
//public int indexOf(int ch)返回指定字符第一次出现的字符串内的索引。
//从0开始到length()-1
//传入的是ASCLL码值
System.out.println(s.indexOf(108)); //2
System.out.println(s.indexOf('l')); //2
System.out.println("***************************");
//public int indexOf(String str)
// 返回指定子字符串第一次出现的字符串内的索引。
//字符串第一个字符索引
System.out.println(s.indexOf("owo")); //4
//当子字符串不存在的时候,返回的是-1
System.out.println(s.indexOf("poi")); //-1
System.out.println("***************************");
// public int indexOf(int ch,int fromIndex)
// 返回指定字符第一次出现的字符串内的索引,以指定的索引开始搜索。
System.out.println(s.indexOf('l',4)); //8
System.out.println(s.indexOf('p',4)); //-1
System.out.println(s.indexOf('l',40)); //-1
System.out.println(s.indexOf('p',40)); //-1
System.out.println("***************************");
//int indexOf(String str,int fromIndex)
//返回指定字符串第一次出现的字符串内的索引,以指定的索引开始搜索。
System.out.println("***************************");
//public String substring(int beginIndex)
// 返回一个字符串,该字符串是此字符串的子字符串。
// 子字符串以指定索引处的字符开头,并扩展到该字符串的末尾。
System.out.println(s.substring(3)); //loworld
// System.out.println(s.substring(20)); //StringIndexOutOfBoundsException
System.out.println("***************************");
//public String substring(int beginIndex,int endIndex)
// 返回一个字符串,该字符串是此字符串的子字符串。
// 子串开始于指定beginIndex并延伸到字符索引endIndex - 1 。
//左闭右开 [ , )
System.out.println(s.substring(4,7)); //owo
System.out.println(s.substring(1,20)); //StringIndexOutOfBoundsException
}
}