《day17_String_StringBuffer》

 1 package cn.itcast.api.string;
 2 
 3 public class StringDemo{
 4     public static void main(String[] args){
 5         //定义一个字符串。
 6         String str = "abcd";
 7 //        str="haha";
 8         System.out.println("str="+str);
 9         
10         //================
11         System.out.println("=======多个引用指向同一个字符串========");
12         String s1 = "itcast";
13         String s2 = "itcast";
14         System.out.println(s1==s2);
15         
16         System.out.println("=======两个内容相同创建方式不同的字符串=======");
17         String s3 = "abc";
18         String s4 = new String("abc");
19         
20         //s3和s4有什么不同呢?
21         /*
22          * s3创建,在内容中只有一个对象。
23          * 
24          * s4创建,在内容中有两个对象。
25          * */
26         System.out.println(s3==s4);
27         System.out.println(s3.equals(s4));//true,因为Strng复写了equals方法,
28         //建立字符串自己的判断相同的依据。是通过字符串对象中的内容
29         //来判断的。
30         
31 
32     }
33 }
 1 package cn.itcast.api.string;
 2 
 3 public class StringDemo2 {
 4     public static void main(String[] args){
 5         
 6         /*
 7          * "abcede"
 8          * 
 9          * 1,字符串是一个对象,那么它的方法必然是围绕操作对象的数据而定义的。
10          * 2,你认为字符串中有哪些功能呢?
11          *     2.1:有多少个字符?
12          *      int length()
13          *  
14          *  2.2:字符的位置。
15          *      int indexOf(char ch)
16          *  2.3:获取所需位置上的字符。
17          *      char charAt(int index)
18          *  2.4:获取部分字符串。
19          *      String substring(int beginIndex, int endIndex) 
20          *  
21          * 
22          * 
23          * */
24         String str = "abcde";
25 //        System.out.println("length="+str.length());
26         int len = str.length();
27         System.out.println("len="+len);
28         
29 //        System.out.println("index="+str.indexOf('d'));
30         int index = str.indexOf('e');
31         System.out.println("index2="+index);
32         
33 //        System.out.println("char="+str.charAt(3));
34         char ch = str.charAt(4);
35         System.out.println("char="+ch);
36         
37 //        System.out.println("subString="+str.substring(2,4));
38         String str1 = str.substring(2, 4);
39         System.out.println("subString="+str1);
40     }
41 }
 1 package cn.itcast.api.string;
 2 
 3 public class StringTest {
 4 
 5     public static void main(String[] args) {
 6         
 7         /*
 8          * Stirng方法查找练习。
 9          * 1,字符串是否以指定字符串开头。结尾同理。
10          *         boolean startsWith(String)
11          *        boolean endsWith(String)
12          *
13          * 2,字符串中是否包含另一个字符串。
14          *         boolean contains(String);
15          *         int indexOf(String)//如果返回-1表示不存在。
16          * 
17          * 3,字符串中另一个字符串出现的位置。
18          *         int indexOf(String)
19          * 
20          * 4,将字符串中指定的字符串替换成另一个字符串。
21          *         String replace(oldString newString);
22          *     
23          * 5,字符串如何比较大小?
24          *         
25          *         
26          * 6,将字符串转成一个字符数组,或者字节数组。
27          *         char[] toCharArray();
28          *         byte[] getBytes();
29          * 
30          * 7,将字母字符串转成大写的字母字符串。
31          *         String toUpperCase()
32          *         String toLowerCase()
33          *         
34          * 8,将字符串按照指定的方式分解成多个字符串,“lisi,wangwu,zhaoliu”获取三个姓名。
35          *         String[] split(String);
36          * */
37         //1
38         String str="StringDemo.java";
39         boolean b1 = str.startsWith("Demo");
40         System.out.println(b1);//false
41         
42         //2
43         boolean b2 = str.contains("Demo");//CharSequence x = "Demo";多态。
44         System.out.println(b2);//true
45         int x = str.indexOf("Demox");//-1 表示不存在。
46         System.out.println(x);
47         
48         //4
49         String s = str.replace("haha", "Test");//没有替换内容时,结果是原串儿。
50         System.out.println("s="+s);
51         
52         //6
53         char[] chs = str.toCharArray();
54         System.out.println(chs);
55         byte[] nums = str.getBytes();
56         System.out.println(nums);
57         
58         //7
59         String upperString = str.toUpperCase();
60         System.out.println(upperString);
61         
62         //8
63         String str2 = "lisi,wangwu,zhangsan";
64         String[] names = str2.split(",");
65         for (int i = 0; i < names.length; i++) {
66             System.out.println(names[i]);
67         }
68         
69         //5,字符串如何比较大小?
70 //        int result = str.compareTo("cd");
71         int result  = "ab".compareTo("cd");//只要想让对象具备比较大小的功能,只需要实现Compareable接口就行了。
72         System.out.println(result);
73     }
74 
75 }
  1 package cn.itcast.api.string;
  2 
  3 import java.util.Arrays;
  4 
  5 public class StringTest2 {
  6 
  7     public static void main(String[] args) {
  8         /*
  9          * 案例一:字符串数组
 10          * {"abc","nba","cctv","itcast"}
 11          * 要求从小到大排序。
 12          * 
 13          */
 14           String[] strs = {"abc","nba","cctv","itcast"};
 15           printArray(strs);
 16           sortString(strs);
 17           printArray(strs);
 18         
 19          /* 
 20          * 案例二:
 21          * "witcasteritcasttyuiitcastodfghjitcast"有几个itcast
 22          * 
 23          * 思路:
 24          * 1,无非就是在一个字符串中查找另一个字符串。indexOf
 25          * 2,查找到第一次出现的指定的字符串后,如何查找第二个呢?
 26          * 3,无需再从头开始,只要从第一次出现的位置加上要找的字符串的长度的位置开始向后查找下一个第一次出现的位置即可。
 27          * 4,当返回位置是-1时,说明查找结束。
 28          */
 29           String str = "witcasteritcasttyuiitcastodfghjitcast";
 30           String key = "itcast";
 31           int count = getKeyCount(str,key);
 32           System.out.println("count="+count);
 33           /*int x = str.indexOf(key,0);//第一次从头开始找。
 34           System.out.println("x="+x);
 35           
 36           int y  = str.indexOf(key,x+key.length());//从指定起始位开始找。
 37           System.out.println("y="+y);
 38           
 39           int z  = str.indexOf(key,y+key.length());//从指定起始位开始找。
 40           System.out.println("z="+z);*/
 41           
 42           
 43           /*
 44          * 案例三:
 45          * “itcast_sh”要求,将该字符串按照长度由长到短打印出来。
 46          * itcast_sh
 47          * itcast_s
 48          * tcast_sh
 49          * 
 50          * 
 51          */
 52           String str1 = "itcast_sh";
 53           printStrinByLength(str1);
 54     }
 55 
 56 
 57 
 58     public static void printStrinByLength(String str1) {
 59         //,通过分析,发现是for嵌套循环。
 60         for (int i = 0; i < str1.length(); i++) {
 61             for(int start = 0,end = str1.length()-i;end <= str1.length();start++,end++){
 62                 //根據start,end截取字符串。
 63                 String  temp = str1.substring(start, end);
 64                 System.out.println(temp);
 65             }
 66         }
 67         
 68     }
 69 
 70 
 71 
 72     /**
 73      * 获取key在str中出现的次数。
 74      * */
 75     public static int getKeyCount(String str, String key) {
 76         //1,定义变量。记录每一次找到的key的位置.
 77         int index = 0;
 78         //2,定义变量,记录出现的次数。
 79         int count = 0;
 80         //3,定义循环。只要索引到的位置不是-1就继续查找。
 81         while((index = str.indexOf(key,index))!=-1){
 82             //每循环一次就要明确下一次查找的起始位置。
 83             index = index+key.length();
 84             
 85             count++;
 86         }
 87         return count;
 88     }
 89 
 90 
 91 
 92     /**
 93      * 字符串排序
 94      * 思路:
 95      * 1,以前有过int[] 排序,选择,冒泡。
 96      * 2,字符串排序同理。
 97      * 3,for嵌套循环。
 98      * 4,循环中进行元素大小比较,满足条件位置置换。
 99      * 
100      * */
101     public static void sortString(String[] strs) {
102         for (int i = 0; i < strs.length; i++) {
103             for (int j = i+1; j < strs.length; j++) {
104                 if(strs[i].compareTo(strs[j])>0){//对象比较用方法。compareTo.
105                     swap(strs,i,j);
106                 }
107             }
108         }
109 //        Arrays.sort(strs);
110     }
111 
112     /**
113      * 数组元素的置换。
114      * 
115      * */
116     private static void swap(String[] strs, int i, int j) {
117         String temp = strs[i];
118         strs[i] = strs[j];
119         strs[j] = temp;
120     }
121     
122     private static void printArray(String[] strs) {
123         for (int i = 0; i < strs.length; i++) {
124             System.out.print(strs[i]+" ");
125         }
126         System.out.println();
127     }
128 }
 1 package cn.itcast.api.stringbuffer;
 2 
 3 public class StringBufferDemo {
 4 
 5     public static void main(String[] args) {
 6         /*
 7          * StirngBuffer:
 8          * 1,是一个字符串缓冲区,其实就是一个容器。
 9          * 2,长度是可变的,任意类型都行。注意:是将任意数据都转成字符串进行存储。
10          * 3,容器中提供了很多对容器中数据的操作功能,添加,删除,修改。
11          * 4,所有的数据最终转成字符串。
12          * 5,和数组最大的不同就是,数组存储完可以单独操作每一个元素,每一个元素都是
13          *    独立的,而字符串缓冲区不是,所有存储的元素都被转成了字符串,而且最后拼成
14          *    了一个大的字符串。
15          * */
16         
17         //1,创建一个字符串缓冲区对象,用于存储数据。
18         StringBuffer sb = new StringBuffer();
19         
20         //2,添加数据。不断的添加数据后,要对缓冲区中的数据进行操作,必须转成字符串。
21         String str = sb.append(true).append("hehe").toString();
22         //sb.append("haah");
23         
24         //sb.insert(2, "it");//在指定位置插入元素。
25         
26         //sb.delete(1, 4);//删除。
27         
28         sb.replace(1, 4, "cast");
29         
30         sb.setLength(2);
31         System.out.println(sb);
32         //System.out.println(sb.reverse());
33         //System.out.println(str);
34         
35         //String s = "a"+5+'c';
36         //底层原理:
37         //s = new StringBuffer().append("a").append(5).append('c').toString();
38     }
39 }
 1 package cn.itcast.api.stringbuffer;
 2 
 3 public class StringBufferTest {
 4 
 5     public static void main(String[] args) {
 6         /*int[] arr = [34,12,89,67];
 7          * 将一个int数组中的元素转成字符串,格式[34,12,89,67]
 8          * 
 9          */
10         int[] arr = {34,12,89,67};
11         String str = toString_2(arr);
12         System.out.println(str);
13     }
14 
15     /**
16      * 缓冲区的应用,无论多少数据,什么类型都不中要,只要最终变成字符串,就可以使用StringBuffer
17      * 
18      * @param arr
19      * @return
20      */
21     public static String toString_2(int[] arr) {
22         //创建缓冲区,
23         StringBuffer sb = new StringBuffer();
24         sb.append("[");
25         for (int i = 0; i < arr.length; i++) {
26             if(i!=arr.length-1){
27                 sb.append(arr[i]+".");
28             }else{
29                 sb.append(arr[i]+"]");
30             }
31         }
32         return sb.toString();
33     }
34 
35     public static String toString(int[] arr) {
36         //用字符串连接。
37         String str = "[";
38         for (int i = 0; i < arr.length; i++) {
39             if(i!=arr.length-1){
40                 str+=arr[i]+",";
41             }else{
42                 str+=arr[i]+"]";
43             }
44         }
45         return str;
46     }
47 }
 1 package cn.itcast.api.stringbuffer;
 2 
 3 public class StringBuilderDemo {
 4 
 5     public static void main(String[] args) {
 6         /*
 7          * StringBuilder 和SringBuffer的区别。
 8          * 
 9          * StringBuilder是非同步的,单线程访问效率高,
10          * StirngBuffer是同步的 ,多线程访问安全。
11          * 
12          */
13     }
14 
15 }
 1 package cn.itcast.comparedemo;
 2 
 3 public class Person implements Comparable{
 4     private String name;
 5     private int age;
 6     public Person() {
 7         super();
 8     }
 9     public Person(String name, int age) {
10         super();
11         this.name = name;
12         this.age = age;
13     }
14     public String getName() {
15         return name;
16     }
17     public void setName(String name) {
18         this.name = name;
19     }
20     public int getAge() {
21         return age;
22     }
23     public void setAge(int age) {
24         this.age = age;
25     }
26     
27     /**
28      * 建立了Person对象判断是否相同的依据,只要是同姓名同年龄就是
29      * 同一个人。
30      * */
31     @Override
32     public boolean equals(Object obj) {
33         if(this == obj)
34         return true;
35         if(!(obj instanceof Person)){
36             throw new ClassCastException("类型错误");
37         }
38         Person p = (Person)obj;
39         return this.name.equals(p.name) && this.age == p.age;
40     }
41     
42     
43     @Override
44     public String toString() {
45         return "Person [name=" + name + ", age=" + age + "]";
46     }
47     
48     /**
49      * 比较年龄大小的方法。
50      * */
51     @Override
52     public int compareTo(Object o) {
53         
54         if(!(o instanceof Person)){
55             throw new ClassCastException("类型错误");
56         }
57         Person p = (Person)o;
58         return this.age - p.age;
59     }
60     
61 }
1 package cn.itcast.comparedemo;
2 
3 public class PersonDemo {
4     public static void main(String[] args){
5         
6     }
7 }
原文地址:https://www.cnblogs.com/sun-/p/5424389.html