String类的基本方法indexOf()和substring()

* String类的获取功能
* 1.int length();获取字符串的长度
* 2.char charAt(int index);获取指定索引位置的字符
* 3.int indexOf(int ch);返回指定字符在此字符串中第一次出现处的索引
* 4.int indexOf(String str);返回指定字符串在此字符串中第一次出现处的索引
* 5.int indexOf(int ch,int fromIndex);返回指定字符在此字符串中从指定位置后第一次出现处的索引
* 6.int indexOf(String str,int fromIndex);返回指定字符串在此字符串中从指定位置后第一次出现处的索引
* 7.lastIndexOf
* 8.String substring(int start);从指定位置开始截取字符串,默认到末尾

* 9.String substring(int start,int end);从指定位置开始到指定位置结束截取字符串

public class DemoString2{

  public static void main(String[] args) {

   String s1="KobeBryante";
   System.out.println(s1.length());
   String s2="科比布莱恩特";
   System.out.println(s2.length());//1.获取字符串的长度

   char c1=s1.charAt(0);
   System.out.println(c1);//2.输出K

   int index=s1.indexOf('K');
   System.out.println(index);//3.输出0
   System.out.println(s1.indexOf('z'));//若不存在则返回-1

   int index1=s1.indexOf("be");
   System.out.println(index1);//4.获取"be"字符串中第一个字符出现的位置
   System.out.println(s1.indexOf("or"));//返回-1

   int index2=s1.indexOf('e',4);

   System.out.println(index2);//5.从指定位置往后找,输出10,从第4个往后找

   int index3=s1.indexOf("nt",4);
   System.out.println(index3);//6.输出8

   int index4=s1.lastIndexOf('e');
   System.out.println(index4);//7.输出10,从后向前找,第一次出现的字符
   System.out.println(s1.indexOf('e'));//输出3

   String str1=s1.substring(4);
   System.out.println(str1);//8.包括4的位置

   String str2=s1.substring(4,6);
   System.out.println(str2);//9.输出Br,包括4不包括6的位置;[4,6)

   //陷阱题
   String s="Kobe";
   s.substring(2);
   System.out.println(s);//打印Kobe,s没变;若System.out.println(s.substring(2));则打印的是be
   System.out.println(s.substring(2));
  }

}


猜你喜欢

转载自blog.csdn.net/zuihongyan518/article/details/80915364