String的用法——获取功能
package cn.itcast_04;
/*
- String类获取功能
- int length():获取字符的长度
- char charAt(int index):获取指定索引位置的字符
- int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引
-
注意:为什么这里是int类型,而不是char类型
-
答:因为97和'a'都代表a;
-
当定义为char ch;时,当我们输入97,是需要强制转换,才能得到'a',
-
而,定义为int ch时,则不需要,输入97,'a'均可
- 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):从指定位置开始到指定位置结束,截取字符串
-
注意:包括第start个字符,不包括第end个字符,即,包左不包右
*/
public class StringDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//定义一个字符串对象
String s = "HelloWorld";
//int length():获取字符的长度
System.out.println("s.length:" + s.length());
System.out.println("-------------------------------------------------");
//char charAt(int index):获取指定索引位置的字符
System.out.println("s.charAt():"+ s.charAt(9));
System.out.println("-------------------------------------------------");
//int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引
System.out.println("s.indexOf():"+ s.indexOf('o'));//4
System.out.println("s.indexOf():"+ s.indexOf('t'));//-1
System.out.println("-------------------------------------------------");
//int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引
System.out.println("s.indexOf():"+ s.indexOf("or"));//6
System.out.println("s.indexOf():"+ s.indexOf("oW"));//4
System.out.println("-------------------------------------------------");
//int indexOf(int ch,int fromIndex):返回指定字符在此字符串指定位置后第一次出现处的索引
System.out.println("s.indexOf():"+ s.indexOf('o',0));//4
System.out.println("s.indexOf():"+ s.indexOf('o',3));//4
System.out.println("s.indexOf():"+ s.indexOf('o',7));//-1
System.out.println("-------------------------------------------------");
//int indexOf(String str,int fromIndex):返回指定字符串在此字符串指定位置后第一次出现处的索引
System.out.println("s.indexOf():"+ s.indexOf("or",0));//6
System.out.println("s.indexOf():"+ s.indexOf("loW",3));//3
System.out.println("s.indexOf():"+ s.indexOf("oW",7));//-1
System.out.println("-------------------------------------------------");
//String substring(int start):从指定位置截取字符串,默认到末尾
System.out.println("substring截取字符串:" + s.substring(3));
System.out.println("substring截取字符串:" + s.substring(0));
System.out.println("-------------------------------------------------");
//String substring(int start,int end):从指定位置开始到指定位置结束,截取字符串
System.out.println("substring截取字符串:" + s.substring(3,6));//loW
System.out.println("substring截取字符串:" + s.substring(0,s.length()));//HelloWorld
System.out.println("-------------------------------------------------");
}
}