String类的获取功能

 1 /*
 2         String类的获取功能:
 3                 int length()
 4                 char charAt(int index)
 5                 int indexOf(int ch)
 6                 int indexOf(String str)
 7                 int indexOf(int ch,int fromIndex)
 8                 int indexOf(String str,int fromIndex)
 9                 String substring(int start)
10                 String substring(int start,int end)
11  */
12 public class StringDemo7 {
13     public static void main(String[] args) {
14         String s = "helloworld";
15 
16         //int length() 获取字符串的长度
17         System.out.println(s.length());
18         System.out.println("***************************");
19 
20         //public char charAt(int index)返回char指定索引处的值
21         //从0开始到length()-1
22         System.out.println(s.charAt(7));
23         System.out.println(s.charAt(0));
24 //        System.out.println(s.charAt(11));//StringIndexOutOfBoundsException
25         System.out.println("***************************");
26 
27         //public int indexOf(int ch)返回指定字符第一次出现的字符串内的索引。
28         //从0开始到length()-1
29         //传入的是ASCLL码值
30         System.out.println(s.indexOf(108)); //2
31         System.out.println(s.indexOf('l')); //2
32         System.out.println("***************************");
33 
34         //public int indexOf(String str)
35         // 返回指定子字符串第一次出现的字符串内的索引。
36         //字符串第一个字符索引
37         System.out.println(s.indexOf("owo")); //4
38         //当子字符串不存在的时候,返回的是-1
39         System.out.println(s.indexOf("poi")); //-1
40         System.out.println("***************************");
41 
42         // public int indexOf(int ch,int fromIndex)
43         // 返回指定字符第一次出现的字符串内的索引,以指定的索引开始搜索。
44         System.out.println(s.indexOf('l',4)); //8
45         System.out.println(s.indexOf('p',4)); //-1
46         System.out.println(s.indexOf('l',40)); //-1
47         System.out.println(s.indexOf('p',40)); //-1
48         System.out.println("***************************");
49 
50         //int indexOf(String str,int fromIndex)
51         //返回指定字符串第一次出现的字符串内的索引,以指定的索引开始搜索。
52         System.out.println("***************************");
53 
54         //public String substring(int beginIndex)
55         // 返回一个字符串,该字符串是此字符串的子字符串。
56         // 子字符串以指定索引处的字符开头,并扩展到该字符串的末尾。
57         System.out.println(s.substring(3)); //loworld
58 //        System.out.println(s.substring(20)); //StringIndexOutOfBoundsException
59         System.out.println("***************************");
60 
61         //public String substring(int beginIndex,int endIndex)
62         // 返回一个字符串,该字符串是此字符串的子字符串。
63         // 子串开始于指定beginIndex并延伸到字符索引endIndex - 1 。
64         //左闭右开  [ , )
65         System.out.println(s.substring(4,7)); //owo
66         System.out.println(s.substring(1,20)); //StringIndexOutOfBoundsException
67 
68 
69 
70 
71     }
72 }

 

posted @ 2021-10-23 21:15  三十而已!  阅读(70)  评论(0)    收藏  举报