package cn.itcast_04;code
/*對象
注意:爲何這裏是int類型,而不是char類型
答:由於97和'a'都表明a;
當定義爲char ch;時,當咱們輸入97,是須要強制轉換,才能獲得'a',
而,定義爲int ch時,則不須要,輸入97,'a'都可
注意:包括第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("-------------------------------------------------"); }
}字符串