黑马程序员---Java基础-String类

来源:互联网 发布:新浪微博广告推广mac 编辑:程序博客网 时间:2024/05/17 04:18

——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-

字符串操作是计算机中最常见的行为。尤其是Java大展拳脚的web系统中
一、不可变String
首先讨论的就是String对象是不可变的。从API文档可以得出,String类中每一个看起来都会修改String值的方法,实际上都是创建了一个新的String对象,以包含修改后的字符内容。而最初的String内容并没有改变,只是变为垃圾了。

二、String的构造方法
1.public String():无参的。构造一个空的字符串对象;内部没有任何的字符;
2.public String(byte[] bytes):通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
3.public String(byte[] bytes,int offset,int length):通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。
4.public String(char[] value):分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。
5.public String(char[] value,int offset,int count)
6.public String(String original):使用参数的String构造一个新的String

代码如下:

public class StringDemo {    public static void main(String[] args) {            byte[] byts={97,98,99,100,101};//a,b,c,d,e        String s1=new String(byts);        System.out.println("s1:"+s1);        System.out.println("---------------------------");        String s2=new String(byts,1,3);        System.out.println("s2:"+s2);        System.out.println("---------------------------");        char[] chs={'a','b','c','你','好'};        String s3=new String(chs);        System.out.println("s3:"+s3);        System.out.println("---------------------------");        String s4=new String(chs,3,2);        System.out.println("s4:"+s4);        System.out.println("---------------------------");        String s5="hello";        System.out.println(s5.length());            }}

程序显示的结果是:
这里写图片描述

三、String的两个面试题
※面试题一:

public class StringTest {    public static void main(String[] args) {        String s1 = new String("hello");        String s2 = new String("hello");        System.out.println(s1 == s2);        System.out.println(s1.equals(s2));        System.out.println("---------------");        String s3=new String("hello");        String s4="hello";        System.out.println(s3==s4);         System.out.println(s3.equals(s4));        System.out.println("---------------");        String s5="hello";        String s6="hello";        System.out.println(s5==s6);        System.out.println(s5.equals(s6));    }}

程序的运行结果是:
这里写图片描述

由于String类的equals()方法重写了父类Object类中的equals方法,重写后的方法比较的就是存储的内容是否相同,所以每一个equals比较的结果都是true。而==符号在比较引用数据类型的时候,比较的是其指向的地址是否相同,因为String类对象的值是不可更改的,所以只有最后一个比较的结果是true。前两个因为都创建了新的对象,所以就是false了。

※面试题二

public class StringTest2 {    public static void main(String[] args) {        String s1="hello";        String s2="world";        String s3="helloworld";        System.out.println(s3==s1+s2);        System.out.println(s3.equals(s1+s2));        System.out.println(s3=="hello"+"world");        System.out.println(s3.equals("hello"+"world"));    }}

程序执行的结果是:
这里写图片描述

这个可能会更令你迷惑了,结果是这样的?只要是将字符串常量值赋给了一个变量,就在常量池里创建了一份空间,地址就会不一样,所以通过变量相加的比较是false的。而字符串直接相加后的比较就是一样的,因为Java虚拟机会去找有没有这样的常量值,有就会直接赋值,所以后面的是true。

四、String类的判断功能
1.boolean equals(Object obj):重写父类的equals。将此字符串与指定的对象比较。当且仅当该参数不为 null,并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。区分大小写的
2.boolean equalsIgnoreCase(String str):将此 String 与另一个 String 比较,不考虑大小写。
3.boolean contains(String str):且仅当此字符串包含指定的 char 值序列时,返回 true。 区分大小写
4.boolean startsWith(String str);测试此字符串是否以指定的前缀开始。 区分大小写
5.boolean endsWith(String str):测试此字符串是否以指定的后缀结束。 区分大小写
6.boolean isEmpty():是否是空的字符序列;

下面是具体的举例:

public class Demo {    public static void main(String[] args) {        String s1 = "abc";        String s2 = "abc";        System.out.println("s1 == s2 : " + (s1 == s2));//true        System.out.println("s1.equals(s2) : " + s1.equals(s2));        String s3 = new String("abc");        String s4 = new String("abc");        System.out.println("s3 == s4 : " + (s3 == s4));//false        System.out.println("s3.equals(s4) : " + s3.equals(s4));//true        String s5 = new String("abc");        String s6 = "abc";        System.out.println("s5 == s6 : " + (s5 == s6));//false        System.out.println("s5.equals(s6) : " + (s5.equals(s6)));//true        String s7 = "abc";        String s8 = "Abc";        System.out.println("s7 == s8 : " + (s7 == s8));//false        System.out.println("s7.equals(s8) : " + s7.equals(s8));//false        //2.boolean equalsIgnoreCase(String str):不区分大小的比较。        String s9 = "abc";        String s10 = "abc";        String s11 = "Abc";        System.out.println("s9.equals(s10) : " + s9.equals(s10));//true        System.out.println("s9.equals(s11) : " + s9.equals(s11));//false        System.out.println("s9.equalsIgnoreCase(s11) : " + s9.equalsIgnoreCase(s11));//true.不区分大小写        //3.boolean contains(String str)        String s12 = "helloWorld";        System.out.println("s12.contains(\"llo\") : " + s12.contains("llo"));//true        System.out.println("s12.contains(\"world\") : " + s12.contains("world"));//false        System.out.println("s12.contains(\"World\") : " + s12.contains("World"));//true        //4.boolean startsWith(String str)和boolean endsWith(String str)        String s13 = "helloWorld";        System.out.println("s13.startsWith(\"h\") : " + s13.startsWith("h"));//true        System.out.println("s13.startsWith(\"H\") : " + s13.startsWith("H"));//false        System.out.println("s13.startsWith(\"hello\") : " + s13.startsWith("hello"));//true        System.out.println("s13.endsWith(\"d\") : " + s13.endsWith("d"));//true        System.out.println("s13.endsWith(\"ld\") : " + s13.endsWith("ld"));//true        System.out.println("s13.endsWith(\"D\") : " + s13.endsWith("D"));//false        //5.boolean isEmpty()        String s14 = null;        String s15 = "";//OK的,空字符串,也就是0长度字符串;    //  System.out.println("s14.isEmpty() : " + s14.isEmpty());//运行时NullPointerException        System.out.println("s15.isEmpty() : " + s15.isEmpty());        String s16 = "helloworld";        System.out.println(s16.contains("hll"));//false        String s17 = new String("hello");        System.out.println(s16.contains(s17));//等效于:s16.contains("hello")    }}

程序执行的结果是:
这里写图片描述

五、String类的获取功能
1.int length():区分数组的length属性
2.char charAt(int index):获取index处的字符
3.int indexOf(int ch):查找某个ch在字符串中第一次出现的索引值。如果没有出现,那么返回-1
4.int indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引
5.int indexOf(int ch,int fromIndex):从fromIndex位置开始找ch
6.int indexOf(String str,int fromIndex)返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
7.String substring(int start):返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
8.String substring(int start,int end):不包含end。start 到 end -1处

代码举例如下:

public class Demo {    public static void main(String[] args) {        String s1 = "helloworld";        System.out.println("s1.length() : " + s1.length());//10        System.out.println("s1.charAr(0) : " + s1.charAt(0));//h        System.out.println("s1.charAr(1) : " + s1.charAt(1));//e        System.out.println("s1.charAr(2) : " + s1.charAt(2));//l        System.out.println("s1.charAr(3) : " + s1.charAt(3));//l        System.out.println("s1.charAr(4) : " + s1.charAt(4));//o        //int indexOf(int ch)        System.out.println("s1.indexOf(101) : " + s1.indexOf(101));        System.out.println("s1.indexOf(108) : " + s1.indexOf(108));        //int indexOf(String str)        System.out.println("s1.indexOf(\"ell\") : " + s1.indexOf("ell"));//1        System.out.println("s1.indexOf(\"o\") : " + s1.indexOf("o"));//4        //int indexOf(int ch,int fromIndex)        System.out.println("s1.indexOf(101,1) : " + s1.indexOf(101,1));//1        System.out.println("s1.indexOf(101,2) : " + s1.indexOf(101,2));//-1        //int indexOf(String str,int fromIndex)        System.out.println("s1.indexOf(\"ell\",0) : " + s1.indexOf("ell",0));//1        System.out.println("s1.indexOf(\"ell\",1) : " + s1.indexOf("ell",1));//1        System.out.println("s1.indexOf(\"ell\",2) : " + s1.indexOf("ell",2));//1        //String substring(int start)        String s2 = "helloworld";        System.out.println("s2.substring(5) : " + s2.substring(5));//一直取到结尾        //String substring(int start,int end)        System.out.println("s2.substring(0,4) : " + s2.substring(0,4));//hell        System.out.println("s2.substring(0,5) : " + s2.substring(0,5));//hello    }}

程序运行的结果是:
这里写图片描述

六、String类的转换功能
1.byte[] getBytes():将字符串转换为byte[]数组
2.char[] toCharArray():将字符串转换为字符数组
3.static String valueOf(char[] chs):将一个char数组转换为一个String。注意:此方法是static的
4.static String valueOf(int i):将一个int转换为一个字符串;
5.String toLowerCase():将字符串中的字符转换为小写字符:原字符串不变
6.String toUpperCase():转换为大写;原字符串不变;
7.String concat(String str):将参数字符串str添加到当前字符串的末尾。生成一个新字符串;效果跟字符串连接(+)一样

代码:

public class Demo {    public static void main(String[] args) {        String s1 = "abc";        byte[] byteArray1 = s1.getBytes();              System.out.println("abc-的byte数组的长度:" + byteArray1.length);//3        System.out.println("abc的byte数组的内容:");        for(int i = 0;i < byteArray1.length;i++){            System.out.println(byteArray1[i]);//97,98,99        }        //2.char[] toCharArray():将字符串转换为字符数组        String s3 = "helloworld";        char[] charArray = s3.toCharArray();        System.out.println("charArray = " + charArray.toString());//地址        System.out.println(charArray);//println(char[] charArray);内部遍历了char数组        int[] intArray = {2,3,4,5};        System.out.println(intArray);//println(Object obj);内部调用的obj.toString();        //3.static String valueOf(char[] chs)        char[] charArray2 = {'a','b','你','好','傻'};        String s4 = String.valueOf(charArray2);        System.out.println("s4 = " + s4);        //4.static String valueOf(int i)        int num = 10;    //  String s5 = num;//编译错误:不兼容的类型;        //转换的方式一:        String s5 = String.valueOf(num);        //转换的方式二:        String s6 = num + "";        System.out.println("s5 = " + s5);        System.out.println("s6 = " + s6);        //5.String toLowerCase()        String s7 = "HelloWorld";        String result = s7.toLowerCase();//生成一个新的字符串        System.out.println("转换为小写:result = " + result);        System.out.println("s7 = " + s7);//原字符串不变        //6.String toUpperCase()        String s8 = "helloWorld";        System.out.println("转换为大写:" + s8.toUpperCase());        //7.String concat(String str)        String s9 = "hello";        String s10 = "world";        String s11 = s9.concat(s10);//作用:s9 + s10;效果一样        System.out.println("s9.concat(s10) : " + s11);        System.out.println("s9 = " + s9);        System.out.println("s10 = " + s10);    }}

程序执行的结果是:
这里写图片描述

七、String类的其他功能
※替换功能
String replace(char old,char new):将字符串中old字符替换为new字符
String replace(String old,String new):将字符串中old字符串替换为new字符串
去除字符串两空格
String trim():作用:从用户那里接收数据,有可能用户不小心在数据的前后加了若干的空格,

※按字典顺序比较两个字符串
int compareTo(String str):按ASCII码值比较。做减法;
int compareToIgnoreCase(String str) :不区分大小写;

程序代码如下:

public class Demo {    public static void main(String[] args) {        String str = "hello";        System.out.println("将小写的l替换为大写的L:" + str.replace('l', 'L'));        System.out.println("将ell替换为ELL : " + str.replace("ell", "ELL"));        System.out.println("str = " + str);        String s2 = " he ";        System.out.println("s2= |" + s2 + "|");        System.out.println("s2去除两边空格后:|" + s2.trim() + "|");        String s3 = " h e ";        System.out.println("s3去除两边空格后:|" + s3.trim() + "|");//不去除中间的空格;        //int compareTo(String str):        String s4 = "a";        String s5 = "b";        String s6 = "a";        String s7 = "c";        System.out.println("a.compareTo(b) : " + s4.compareTo(s5));//-1.a < b        System.out.println("a.compareTo(c) : " + s4.compareTo(s7));//-2:a < c        System.out.println("b.compareTo(a) : " + s5.compareTo(s4));//1: b > a        System.out.println("c.compareTo(a) : " + s7.compareTo(s4));//2: c > a        System.out.println("a.compareTo(a) : " + s4.compareTo(s6));//0: a = a        String s8 = "abc";        String s9 = "acb";        System.out.println("abc.compareTo(acb) : " + s8.compareTo(s9));//-1        String s10 = "abc";        String s11 = "abcdef";        System.out.println("abc.compareTo(abcd) : " + s10.compareTo(s11));//-3:"abc".length() - "abcdef".length()        String s12 = "ABC";        String s13 = "abc";        System.out.println("ABC.compareTo(abc) : " + s12.compareTo(s13));//-32        System.out.println("ABC.compareToIgnoreCase(abc) : " + s12.compareToIgnoreCase(s13));//0    }}

程序执行的结果是:
这里写图片描述

八、String类的一些练习
※统计字符串中大写、小写和数字字符的个数
程序设计的思路:
1.需要三个变量分别存储大写字符,小写字符、数字字符的数量;
2.遍历字符串,首先取出每个字符,接着判断大写、小写、数字,最后将相应的变量自增;
3.打印每种字符的数量
程序:

public class Demo {    public static void main(String[] args) {        String str = "hello";        System.out.println("将小写的l替换为大写的L:" + str.replace('l', 'L'));        System.out.println("将ell替换为ELL : " + str.replace("ell", "ELL"));        System.out.println("str = " + str);        String s2 = " he ";        System.out.println("s2= |" + s2 + "|");        System.out.println("s2去除两边空格后:|" + s2.trim() + "|");        String s3 = " h e ";        System.out.println("s3去除两边空格后:|" + s3.trim() + "|");//不去除中间的空格;        //int compareTo(String str):        String s4 = "a";        String s5 = "b";        String s6 = "a";        String s7 = "c";        System.out.println("a.compareTo(b) : " + s4.compareTo(s5));//-1.a < b        System.out.println("a.compareTo(c) : " + s4.compareTo(s7));//-2:a < c        System.out.println("b.compareTo(a) : " + s5.compareTo(s4));//1: b > a        System.out.println("c.compareTo(a) : " + s7.compareTo(s4));//2: c > a        System.out.println("a.compareTo(a) : " + s4.compareTo(s6));//0: a = a        String s8 = "abc";        String s9 = "acb";        System.out.println("abc.compareTo(acb) : " + s8.compareTo(s9));//-1        String s10 = "abc";        String s11 = "abcdef";        System.out.println("abc.compareTo(abcd) : " + s10.compareTo(s11));//-3:"abc".length() - "abcdef".length()        String s12 = "ABC";        String s13 = "abc";        System.out.println("ABC.compareTo(abc) : " + s12.compareTo(s13));//-32        System.out.println("ABC.compareToIgnoreCase(abc) : " + s12.compareToIgnoreCase(s13));//0    }}

程序运行的结果是:
这里写图片描述

※字符串反转
程序设计的思路:
1.接收字符串;
2.倒序遍历字符串;
3.取出每个字符,拼装到一个字符串中
代码:

public class Demo {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        System.out.print("请输入一个字符串,我为你倒序输出:");        String str = sc.next();        String temp = "";        for(int i = str.length() - 1 ;i >= 0 ; i--){            char c =str.charAt(i);            temp += c;        }        System.out.println("倒序后:" + temp);    }    public static void reverse(){        String s="fasger";        for(int x=0;x<s.length()-1;x++){        }    }}

程序执行的结果是:
这里写图片描述

※模拟用户登录

模拟登录的程序设计思路是:
1.预定义两个变量,代表已经存在的用户名和密码;
2.定义变量,做计数器;
3.使用循环
具体的代码如下:

public class Demo {    public static void main(String[] args) {        //1.预定义两个变量,代表已经存在的用户名和密码;        String loginName = "admin";        String loginPwd = "123456";        //2.定义变量,做计数器;        int count = 3;        Scanner sc = new Scanner(System.in);        //3.循环        while(true){            System.out.print("请输入用户名:");            String uName = sc.next();            System.out.print("请输入登录密码:");            String uPwd = sc.next();            //判断            if(uName.equals(loginName) && uPwd.equals(loginPwd)){                System.out.println("你已登录系统!!");                break;            }else{                //大家注意下面三个步骤的顺序;                count--;                //判断一下计数器                if(count == 0){                    System.out.println("你已尝试三次登录失败,系统结束!");                    break;                }                System.out.println("用户名或密码错误,你还有:" + count + " 次机会!");            }        }    }}

程序执行的结果是:
这里写图片描述

0 0