码迷,mamicode.com
首页 > 编程语言 > 详细

Java笔记(12):常见对象String

时间:2017-05-28 00:25:59      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:字节数组   pass   get   gtest   区分大小写   开始   不能   username   模拟登录   

1、String类的构造方法

 1 package cn.itcast_01;
 2 
 3 /*
 4  * 字符串:就是由多个字符组成的一串数据。也可以看成是一个字符数组。
 5  * 通过查看API,我们可以知道
 6  *         A:字符串字面值"abc"也可以看成是一个字符串对象。
 7  *         B:字符串是常量,一旦被赋值,就不能被改变。
 8  * 
 9  * 构造方法:
10  *         public String():空构造
11  *        public String(byte[] bytes):把字节数组转成字符串
12  *        public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串
13  *        public String(char[] value):把字符数组转成字符串
14  *        public String(char[] value,int index,int count):把字符数组的一部分转成字符串
15  *        public String(String original):把字符串常量值转成字符串
16  *
17  * 字符串的方法:
18  *         public int length():返回此字符串的长度。
19  */
20 public class StringDemo {
21     public static void main(String[] args) {
22         // public String():空构造
23         String s1 = new String();
24         System.out.println("s1:" + s1);
25         System.out.println("s1.length():" + s1.length());
26         System.out.println("--------------------------");
27 
28         // public String(byte[] bytes):把字节数组转成字符串
29         byte[] bys = { 97, 98, 99, 100, 101 };
30         String s2 = new String(bys);
31         System.out.println("s2:" + s2);
32         System.out.println("s2.length():" + s2.length());
33         System.out.println("--------------------------");
34 
35         // public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串
36         // 我想得到字符串"bcd"
37         String s3 = new String(bys, 1, 3);
38         System.out.println("s3:" + s3);
39         System.out.println("s3.length():" + s3.length());
40         System.out.println("--------------------------");
41 
42         // public String(char[] value):把字符数组转成字符串
43         char[] chs = { ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘爱‘, ‘林‘, ‘亲‘ };
44         String s4 = new String(chs);
45         System.out.println("s4:" + s4);
46         System.out.println("s4.length():" + s4.length());
47         System.out.println("--------------------------");
48 
49         // public String(char[] value,int index,int count):把字符数组的一部分转成字符串
50         String s5 = new String(chs, 2, 4);
51         System.out.println("s5:" + s5);
52         System.out.println("s5.length():" + s5.length());
53         System.out.println("--------------------------");
54         
55         //public String(String original):把字符串常量值转成字符串
56         String s6 = new String("abcde");
57         System.out.println("s6:" + s6);
58         System.out.println("s6.length():" + s6.length());
59         System.out.println("--------------------------");
60         
61         //字符串字面值"abc"也可以看成是一个字符串对象。
62         String s7 = "abcde";
63         System.out.println("s7:"+s7);
64         System.out.println("s7.length():"+s7.length());
65     }
66 }

2、String的特点一旦被赋值就不能改变

 1 package cn.itcast_02;
 2 
 3 /*
 4  * 字符串的特点:一旦被赋值,就不能改变。
 5  */
 6 public class StringDemo {
 7     public static void main(String[] args) {
 8         String s = "hello";
 9         s += "world";
10         System.out.println("s:" + s); // helloworld
11     }
12 }

技术分享

3、String字面值对象和构造方法创建对象的区别

 1 package cn.itcast_02;
 2 
 3 /*
 4  * String s = new String(“hello”)和String s = “hello”;的区别?
 5  * 有。前者会创建2个对象,后者创建1个对象。
 6  * 
 7  * ==:比较引用类型比较的是地址值是否相同
 8  * equals:比较引用类型默认也是比较地址值是否相同,而String类重写了equals()方法,比较的是内容是否相同。
 9  */
10 public class StringDemo2 {
11     public static void main(String[] args) {
12         String s1 = new String("hello");
13         String s2 = "hello";
14 
15         System.out.println(s1 == s2);// false
16         System.out.println(s1.equals(s2));// true
17     }
18 }

练习:

 1 package cn.itcast_02;
 2 
 3 /*
 4  * 看程序写结果
 5  */
 6 public class StringDemo3 {
 7     public static void main(String[] args) {
 8         String s1 = new String("hello");
 9         String s2 = new String("hello");
10         System.out.println(s1 == s2);// false
11         System.out.println(s1.equals(s2));// true
12 
13         String s3 = new String("hello");
14         String s4 = "hello";
15         System.out.println(s3 == s4);// false
16         System.out.println(s3.equals(s4));// true
17 
18         String s5 = "hello";
19         String s6 = "hello";
20         System.out.println(s5 == s6);// true
21         System.out.println(s5.equals(s6));// true
22     }
23 }
 1 package cn.itcast_02;
 2 
 3 /*
 4  * 看程序写结果
 5  * 字符串如果是变量相加,先开空间,在拼接。
 6  * 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建。
 7  */
 8 public class StringDemo4 {
 9     public static void main(String[] args) {
10         String s1 = "hello";
11         String s2 = "world";
12         String s3 = "helloworld";
13         System.out.println(s3 == s1 + s2);// false
14         System.out.println(s3.equals((s1 + s2)));// true
15 
16         System.out.println(s3 == "hello" + "world");// false 这个我们错了,应该是true
17         System.out.println(s3.equals("hello" + "world"));// true
18 
19         // 通过反编译看源码,我们知道这里已经做好了处理。
20         // System.out.println(s3 == "helloworld");
21         // System.out.println(s3.equals("helloworld"));
22     }
23 }

4、String类的判断功能

 1 package cn.itcast_03;
 2 
 3 /*
 4  * String类的判断功能:
 5  * boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
 6  * boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写
 7  * boolean contains(String str):判断大字符串中是否包含小字符串
 8  * boolean startsWith(String str):判断字符串是否以某个指定的字符串开头
 9  * boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾
10  * boolean isEmpty():判断字符串是否为空。
11  * 
12  * 注意:
13  *         字符串内容为空和字符串对象为空。
14  *         String s = "";
15  *         String s = null;
16  */
17 public class StringDemo {
18     public static void main(String[] args) {
19         // 创建字符串对象
20         String s1 = "helloworld";
21         String s2 = "helloworld";
22         String s3 = "HelloWorld";
23 
24         // boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
25         System.out.println("equals:" + s1.equals(s2));
26         System.out.println("equals:" + s1.equals(s3));
27         System.out.println("-----------------------");
28 
29         // boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写
30         System.out.println("equals:" + s1.equalsIgnoreCase(s2));
31         System.out.println("equals:" + s1.equalsIgnoreCase(s3));
32         System.out.println("-----------------------");
33 
34         // boolean contains(String str):判断大字符串中是否包含小字符串
35         System.out.println("contains:" + s1.contains("hello"));
36         System.out.println("contains:" + s1.contains("hw"));
37         System.out.println("-----------------------");
38 
39         // boolean startsWith(String str):判断字符串是否以某个指定的字符串开头
40         System.out.println("startsWith:" + s1.startsWith("h"));
41         System.out.println("startsWith:" + s1.startsWith("hello"));
42         System.out.println("startsWith:" + s1.startsWith("world"));
43         System.out.println("-----------------------");
44 
45         // 练习:boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾这个自己玩
46 
47         // boolean isEmpty():判断字符串是否为空。
48         System.out.println("isEmpty:" + s1.isEmpty());
49 
50         String s4 = "";
51         String s5 = null;
52         System.out.println("isEmpty:" + s4.isEmpty());
53         // NullPointerException
54         // s5对象都不存在,所以不能调用方法,空指针异常
55         System.out.println("isEmpty:" + s5.isEmpty());
56     }
57 }

练习:模拟登录

 1 package cn.itcast_03;
 2 
 3 import java.util.Scanner;
 4 
 5 /*
 6  * 模拟登录,给三次机会,并提示还有几次。
 7  * 
 8  * 分析:
 9  *         A:定义用户名和密码。已存在的。
10  *         B:键盘录入用户名和密码。
11  *         C:比较用户名和密码。
12  *             如果都相同,则登录成功
13  *             如果有一个不同,则登录失败
14  *         D:给三次机会,用循环改进,最好用for循环。
15  */
16 public class StringTest {
17     public static void main(String[] args) {
18         // 定义用户名和密码。已存在的。
19         String username = "admin";
20         String password = "admin";
21 
22         // 给三次机会,用循环改进,最好用for循环。
23         for (int x = 0; x < 3; x++) {
24             // x=0,1,2
25             // 键盘录入用户名和密码。
26             Scanner sc = new Scanner(System.in);
27             System.out.println("请输入用户名:");
28             String name = sc.nextLine();
29             System.out.println("请输入密码:");
30             String pwd = sc.nextLine();
31 
32             // 比较用户名和密码。
33             if (name.equals(username) && pwd.equals(password)) {
34                 // 如果都相同,则登录成功
35                 System.out.println("登录成功");
36                 break;
37             } else {
38                 // 如果有一个不同,则登录失败
39                 // 2,1,0
40                 // 如果是第0次,应该换一种提示
41                 if ((2 - x) == 0) {
42                     System.out.println("帐号被锁定,请与班长联系");
43                 } else {
44                     System.out.println("登录失败,你还有" + (2 - x) + "次机会");
45                 }
46             }
47         }
48     }
49 }

练习:模拟登录改进

 1 package cn.itcast_03;
 2 
 3 import java.util.Scanner;
 4 
 5 /*
 6  * 这时猜数字小游戏的代码
 7  */
 8 public class GuessNumberGame {
 9     private GuessNumberGame() {
10     }
11 
12     public static void start() {
13         // 产生一个随机数
14         int number = (int) (Math.random() * 100) + 1;
15 
16         while (true) {
17             // 键盘录入数据
18             Scanner sc = new Scanner(System.in);
19             System.out.println("请输入你要猜的数据(1-100):");
20             int guessNumber = sc.nextInt();
21 
22             // 判断
23             if (guessNumber > number) {
24                 System.out.println("你猜的数据" + guessNumber + "大了");
25             } else if (guessNumber < number) {
26                 System.out.println("你猜的数据" + guessNumber + "小了");
27             } else {
28                 System.out.println("恭喜你,猜中了");
29                 break;
30             }
31         }
32     }
33 }
 1 package cn.itcast_03;
 2 
 3 import java.util.Scanner;
 4 
 5 /*
 6  * 模拟登录,给三次机会,并提示还有几次。如果登录成功,就可以玩猜数字小游戏了。
 7  * 
 8  * 分析:
 9  *         A:定义用户名和密码。已存在的。
10  *         B:键盘录入用户名和密码。
11  *         C:比较用户名和密码。
12  *             如果都相同,则登录成功
13  *             如果有一个不同,则登录失败
14  *         D:给三次机会,用循环改进,最好用for循环。
15  */
16 public class StringTest2 {
17     public static void main(String[] args) {
18         // 定义用户名和密码。已存在的。
19         String username = "admin";
20         String password = "admin";
21 
22         // 给三次机会,用循环改进,最好用for循环。
23         for (int x = 0; x < 3; x++) {
24             // x=0,1,2
25             // 键盘录入用户名和密码。
26             Scanner sc = new Scanner(System.in);
27             System.out.println("请输入用户名:");
28             String name = sc.nextLine();
29             System.out.println("请输入密码:");
30             String pwd = sc.nextLine();
31 
32             // 比较用户名和密码。
33             if (name.equals(username) && pwd.equals(password)) {
34                 // 如果都相同,则登录成功
35                 System.out.println("登录成功,开始玩游戏");
36                 //猜数字游戏
37                 GuessNumberGame.start();
38                 break;
39             } else {
40                 // 如果有一个不同,则登录失败
41                 // 2,1,0
42                 // 如果是第0次,应该换一种提示
43                 if ((2 - x) == 0) {
44                     System.out.println("帐号被锁定,请与班长联系");
45                 } else {
46                     System.out.println("登录失败,你还有" + (2 - x) + "次机会");
47                 }
48             }
49         }
50     }
51 }

 5、String类的获取功能

 1 package cn.itcast_04;
 2 
 3 /*
 4  * String类的获取功能
 5  * int length():获取字符串的长度。
 6  * char charAt(int index):获取指定索引位置的字符
 7  * int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。
 8  *         为什么这里是int类型,而不是char类型?
 9  *         原因是:‘a‘和97其实都可以代表‘a‘
10  * int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。
11  * int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。
12  * int indexOf(String str,int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
13  * String substring(int start):从指定位置开始截取字符串,默认到末尾。
14  * String substring(int start,int end):从指定位置开始到指定位置结束截取字符串。
15  */
16 public class StringDemo {
17     public static void main(String[] args) {
18         // 定义一个字符串对象
19         String s = "helloworld";
20 
21         // int length():获取字符串的长度。
22         System.out.println("s.length:" + s.length());
23         System.out.println("----------------------");
24 
25         // char charAt(int index):获取指定索引位置的字符
26         System.out.println("charAt:" + s.charAt(7));
27         System.out.println("----------------------");
28 
29         // int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。
30         System.out.println("indexOf:" + s.indexOf(‘l‘));
31         System.out.println("----------------------");
32 
33         // int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。
34         System.out.println("indexOf:" + s.indexOf("owo"));
35         System.out.println("----------------------");
36 
37         // int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。
38         System.out.println("indexOf:" + s.indexOf(‘l‘, 4));
39         System.out.println("indexOf:" + s.indexOf(‘k‘, 4)); // -1
40         System.out.println("indexOf:" + s.indexOf(‘l‘, 40)); // -1
41         System.out.println("----------------------");
42 
43         // 自己练习:int indexOf(String str,int
44         // fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
45 
46         // String substring(int start):从指定位置开始截取字符串,默认到末尾。包含start这个索引
47         System.out.println("substring:" + s.substring(5));
48         System.out.println("substring:" + s.substring(0));
49         System.out.println("----------------------");
50 
51         // String substring(int start,int
52         // end):从指定位置开始到指定位置结束截取字符串。包括start索引但是不包end索引
53         System.out.println("substring:" + s.substring(3, 8));
54         System.out.println("substring:" + s.substring(0, s.length()));
55     }
56 }

 6、字符串的遍历

 1 package cn.itcast_04;
 2 
 3 /*
 4  * 需求:遍历获取字符串中的每一个字符
 5  * 
 6  * 分析:
 7  *         A:如何能够拿到每一个字符呢?
 8  *             char charAt(int index)
 9  *         B:我怎么知道字符到底有多少个呢?
10  *             int length()
11  */
12 public class StringTest {
13     public static void main(String[] args) {
14         // 定义字符串
15         String s = "helloworld";
16         for (int x = 0; x < s.length(); x++) {
17             // char ch = s.charAt(x);
18             // System.out.println(ch);
19             // 仅仅是输出,我就直接输出了
20             System.out.println(s.charAt(x));
21         }
22     }
23 }

练习:统计大写,小写及数字字符的个数案例

 1 package cn.itcast_04;
 2 
 3 /*
 4  * 需求:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
 5  * 举例:
 6  *         "Hello123World"
 7  * 结果:
 8  *         大写字符:2个
 9  *         小写字符:8个
10  *         数字字符:3个
11  * 
12  * 分析:
13  *         前提:字符串要存在
14  *         A:定义三个统计变量
15  *             bigCount=0
16  *             smallCount=0
17  *             numberCount=0
18  *         B:遍历字符串,得到每一个字符。
19  *             length()和charAt()结合
20  *         C:判断该字符到底是属于那种类型的
21  *             大:bigCount++
22  *             小:smallCount++
23  *             数字:numberCount++
24  * 
25  *             这道题目的难点就是如何判断某个字符是大的,还是小的,还是数字的。
26  *             ASCII码表:
27  *                 0    48
28  *                 A    65
29  *                 a    97
30  *             虽然,我们按照数字的这种比较是可以的,但是想多了,有比这还简单的
31  *                 char ch = s.charAt(x);
32  * 
33  *                 if(ch>=‘0‘ && ch<=‘9‘) numberCount++
34  *                 if(ch>=‘a‘ && ch<=‘z‘) smallCount++
35  *                 if(ch>=‘A‘ && ch<=‘Z‘) bigCount++
36  *        D:输出结果。
37  *
38  * 练习:把给定字符串的方式,改进为键盘录入字符串的方式。
39  */
40 public class StringTest2 {
41     public static void main(String[] args) {
42         //定义一个字符串
43         String s = "Hello123World";
44         
45         //定义三个统计变量
46         int bigCount = 0;
47         int smallCount = 0;
48         int numberCount = 0;
49         
50         //遍历字符串,得到每一个字符。
51         for(int x=0; x<s.length(); x++){
52             char ch = s.charAt(x);
53             
54             //判断该字符到底是属于那种类型的
55             if(ch>=‘a‘ && ch<=‘z‘){
56                 smallCount++;
57             }else if(ch>=‘A‘ && ch<=‘Z‘){
58                 bigCount++;
59             }else if(ch>=‘0‘ && ch<=‘9‘){
60                 numberCount++;
61             }
62         }
63         
64         //输出结果。
65         System.out.println("大写字母"+bigCount+"个");
66         System.out.println("小写字母"+smallCount+"个");
67         System.out.println("数字"+numberCount+"个");
68     }
69 }

7、String类的转换功能

 1 package cn.itcast_05;
 2 
 3 /*
 4  * String的转换功能:
 5  * byte[] getBytes():把字符串转换为字节数组。
 6  * char[] toCharArray():把字符串转换为字符数组。
 7  * static String valueOf(char[] chs):把字符数组转成字符串。
 8  * static String valueOf(int i):把int类型的数据转成字符串。
 9  *         注意:String类的valueOf方法可以把任意类型的数据转成字符串。
10  * String toLowerCase():把字符串转成小写。
11  * String toUpperCase():把字符串转成大写。
12  * String concat(String str):把字符串拼接。
13  */
14 public class StringDemo {
15     public static void main(String[] args) {
16         // 定义一个字符串对象
17         String s = "JavaSE";
18 
19         // byte[] getBytes():把字符串转换为字节数组。
20         byte[] bys = s.getBytes();
21         for (int x = 0; x < bys.length; x++) {
22             System.out.println(bys[x]);
23         }
24         System.out.println("----------------");
25 
26         // char[] toCharArray():把字符串转换为字符数组。
27         char[] chs = s.toCharArray();
28         for (int x = 0; x < chs.length; x++) {
29             System.out.println(chs[x]);
30         }
31         System.out.println("----------------");
32 
33         // static String valueOf(char[] chs):把字符数组转成字符串。
34         String ss = String.valueOf(chs);
35         System.out.println(ss);
36         System.out.println("----------------");
37 
38         // static String valueOf(int i):把int类型的数据转成字符串。
39         int i = 100;
40         String sss = String.valueOf(i);
41         System.out.println(sss);
42         System.out.println("----------------");
43 
44         // String toLowerCase():把字符串转成小写。
45         System.out.println("toLowerCase:" + s.toLowerCase());
46         System.out.println("s:" + s);
47         // System.out.println("----------------");
48         // String toUpperCase():把字符串转成大写。
49         System.out.println("toUpperCase:" + s.toUpperCase());
50         System.out.println("----------------");
51 
52         // String concat(String str):把字符串拼接。
53         String s1 = "hello";
54         String s2 = "world";
55         String s3 = s1 + s2;
56         String s4 = s1.concat(s2);
57         System.out.println("s3:"+s3);
58         System.out.println("s4:"+s4);
59     }
60 }

练习:

 1 package cn.itcast_05;
 2 
 3 /*
 4  * 需求:把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符)
 5  * 举例:
 6  *         helloWORLD
 7  * 结果:
 8  *         Helloworld
 9  * 
10  * 分析:
11  *         A:先获取第一个字符
12  *         B:获取除了第一个字符以外的字符
13  *         C:把A转成大写
14  *         D:把B转成小写
15  *         E:C拼接D
16  */
17 public class StringTest {
18     public static void main(String[] args) {
19         // 定义一个字符串
20         String s = "helloWORLD";
21 
22         // 先获取第一个字符
23         String s1 = s.substring(0, 1);
24         // 获取除了第一个字符以外的字符
25         String s2 = s.substring(1);
26         // 把A转成大写
27         String s3 = s1.toUpperCase();
28         // 把B转成小写
29         String s4 = s2.toLowerCase();
30         // C拼接D
31         String s5 = s3.concat(s4);
32         System.out.println(s5);
33 
34         // 优化后的代码
35         // 链式编程
36         String result = s.substring(0, 1).toUpperCase()
37                 .concat(s.substring(1).toLowerCase());
38         System.out.println(result);
39     }
40 }

8、String类的其他功能

 1 package cn.itcast_06;
 2 
 3 /*
 4  * String类的其他功能:
 5  * 
 6  * 替换功能:
 7  * String replace(char old,char new)
 8  * String replace(String old,String new)
 9  *
10  * 去除字符串两空格    
11  * String trim()
12  * 
13  * 按字典顺序比较两个字符串  
14  * int compareTo(String str)
15  * int compareToIgnoreCase(String str)
16  */
17 public class StringDemo {
18     public static void main(String[] args) {
19         // 替换功能
20         String s1 = "helloworld";
21         String s2 = s1.replace(‘l‘, ‘k‘);
22         String s3 = s1.replace("owo", "ak47");
23         System.out.println("s1:" + s1);
24         System.out.println("s2:" + s2);
25         System.out.println("s3:" + s3);
26         System.out.println("---------------");
27 
28         // 去除字符串两空格
29         String s4 = " hello world  ";
30         String s5 = s4.trim();
31         System.out.println("s4:" + s4 + "---");
32         System.out.println("s5:" + s5 + "---");
33 
34         // 按字典顺序比较两个字符串
35         String s6 = "hello";
36         String s7 = "hello";
37         String s8 = "abc";
38         String s9 = "xyz";
39         System.out.println(s6.compareTo(s7));// 0
40         System.out.println(s6.compareTo(s8));// 7
41         System.out.println(s6.compareTo(s9));// -16
42     }
43 }

 

Java笔记(12):常见对象String

标签:字节数组   pass   get   gtest   区分大小写   开始   不能   username   模拟登录   

原文地址:http://www.cnblogs.com/lz2lhy/p/6914103.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!