JAVASE 小白学习笔记 (12-2)Java中的常用类--String类

1.String类的引入

String类指的是字符串类,字符串有一个或者多个字符组成的有序序列,从做往由每一个字符从0开始都编有索引。

String类有两大特点,在下面表格中做以陈述:

String类的两大特点
Java程序中的所有字符串字面值(如"abc")都可以作为此类的实例实现
字符串是常量,他们的值在创建后不能进行更改
public class Demo {
    
    
    public static void main(String[] args) {
    
    
        /*Java程序中的所有字符串字面值(如"abc")
          都可以作为此类的实例实现
          可以将其理解为字符串可以直接看作String类的对象,
          可以直接调用String类的方法
 
         */
        int length = "abc".length();
        System.out.println(length);   //3

    }
}

2.String类的常用构造方法

String类的常用构造方法
String():初始化一个新创建的String对象,使其表示一个空字符序列。空构造。
String(String original):初始化一个新创建的String对象,使其表示一个与参数相同的字符序列;换句话说,新创建的字符串是该参数字符串的副本。把字符串常量值转成字符串。
public class Demo1 {
    
    
    public static void main(String[] args) {
    
    
        //String():初始化一个创建的String对象,使其表示一个空字符序列
        String s = new String();
        //打印对象名:1.地址值2.其他(重写过toString()方法)
        //String类重写了toString()方法,会返回字符串表面的内容
        //这里输出的为空串
        System.out.println(s);   //""
        System.out.println("======================");
        /*String(String original):初始化一个新创建的String对象,
        使其表示一个参数相同的字符序列;换句话说,新创建的字符串是
        该参数字符串的副本
         */
        String s1 = new String("abc");
        System.out.println(s1);    //"abc"
        int length = s1.length();
        System.out.println(length);   //3
    }
}

构造方法 作用
public String(byte[] bytes) 把字节数组转成字符串
public String(byte[] bytes,int index,int length) 把字节数组的一部分转成字符串(index:表示的是从第几个索引开始, length表示的是长度)
public String(char[] value) 把字符数组转成字符串
public String(char[] value,int index,int count) 把字符数组的一部分转成字符串
public class Demo2 {
    
    
    public static void main(String[] args) {
    
    
        //public String(byte[] bytes):把字节数组转成字符串
        byte[] bytes = {
    
    97, 98, 99};  //字符a的ACSII码值为97
        String s = new String(bytes);
        System.out.println(s);    //"abc"

        System.out.println("============");
        byte[] bytes1 = {
    
    -25, -120, -79};
        String s1 = new String(bytes1);
        System.out.println(s1);//"爱"
    }
}
public class Demo3 {
    
    
    public static void main(String[] args) {
    
    
        /*public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串
        (index:表示的是从第几个索引开始, length表示的是长度)
         */
        byte[] bytes = {
    
    97, 98, 99, 100};
        //从字节数组的0索引处开始转换,转换两个字节
        String s = new String(bytes, 0, 2);
        System.out.println(s);//"ab"
    }
}
public class Demo4 {
    
    
    public static void main(String[] args) {
    
    
        //pubic String(char [] value):把字符数组转换为字符串
        char[] chars = {
    
    'a', 'b', 'c', '我', '爱', '你'};
        /*//可以通过自己手动将字符数组转换为字符串
        String s = new String();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            s+=c;
        }
        System.out.println(s);  */
        String s = new String(chars);
        System.out.println(s);  //"abc我爱你"

        System.out.println("================");
        //public String(char[] value,int index,int count):把字符数组的一部分转成字符串
        String s1 = new String(chars, 0, 3);
        System.out.println(s1);//"abc"

    }
}

3.String类的特点

String的特点: 一旦被创建就不能改变,因为字符串的值是在堆内存的常量池中划分空间,分配地址值的。

  • 定义字符串有两种方式:1.通过字面值进行赋值 2.通过new关键字创建新对象
public class Demo {
    
    
    public static void main(String[] args) {
    
    
        //定义字符串有两种方式:
        //1."字面值"进行赋值
        String s="abc";
        int length = s.length();
        System.out.println(length);
        System.out.println("============");
        //2.通过new关键字创建新对象
        String s1 = new String("abc");
        int length1 = s1.length();
        System.out.println(length1);
    }
}


  • 面试题:
    String s = “hello” ;
    s = “world” + “java”; 问s的结果是多少?
public class Demo1 {
    
    
    public static void main(String[] args) {
    
    
        String s="hello";
        s="world"+"java";
        System.out.println(s);// "worldjava"
    }
}

那么如何理解"字符串是常量,它们的值在创建之后不能更改"这句话?

  • 想要理解"字符串是常量,他们的值在创建之后不能更改",就需要画内存图进行理解。

在这里插入图片描述

  • 字符串是常量,一旦被定义,就不能被修改,指的是字符串的值不能被改变,所能改变的是指向。总结为:内容不改变,引用可以变。

  • new的方式创建字符串
public class Demo2 {
    
    
    public static void main(String[] args) {
    
    
        //这行代码创建了几个对象?    2个
        String s=new String("hello");
        System.out.println(s);//hello
    }
}
  • 通过构造方法new的方式创建字符串,通过画内存图进行分析创建几个对象。
    在这里插入图片描述

  • 面试题:分析下面的字符串的定义,创建几个对象?通过画内存图进行解释
public class Demo3 {
    
    
    public static void main(String[] args) {
    
    
        //下面的代码中创建了几个对象
        //创建2个对象
        String s1="hello";
        String s2="world";
        String s3="hello";

        System.out.println(s1==s2);    //false
        System.out.println(s1==s3);    //true
    }
}

在这里插入图片描述

  • 注意:当你采用字面量的方式,去定义一个字符串时,会先去字符串常量池中有没有该字符串 。如果没有,就构建一个字符串对象,并把这个对象的地址值,放到String pool中。如果有,就不会重复去构建这个字符串,它是将String pool中的地址值,给到一个字符串引用就可以了

面试题1

public class Demo4 {
    
    
    public static void main(String[] args) {
    
    
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1==s2);      //false
        System.out.println(s1.equals(s2));   //true

        System.out.println("===============");
        String s3 = new String("hello");
        String s4="hello";
        System.out.println(s3==s4);    //false
        System.out.println(s3.equals(s4));  //true


        System.out.println("===============");
        String s5="hello";
        String s6="hello";
        System.out.println(s5==s6);    //true
        System.out.println(s5.equals(s6));   //true
    }
}

面试题2

public class Demo5 {
    
    
    public static void main(String[] args) {
    
    
        String s1="Hello";
        String s2="Hello";
        String s3="Hel"+"lo";
        String s4="Hel"+new String("lo");
        String s5=new String("Hello");
        String s6=s5.intern();
        String s7="H";
        String s8="ello";
        String s9=s7+s8;

        System.out.println(s1==s2);    //true
        System.out.println(s1==s3);    //true
        System.out.println(s1==s4);   //false
        System.out.println(s1==s9);   //false
        System.out.println(s4==s5);   //false
        System.out.println(s1==s6);  //true
    }
}

解析:

  • s1在创建对象的同时,在字符串池中也创建了其对象的引用。
  • 由于s2也是利用字面量创建,所以会先去字符串池中寻找是否有相等的字符串,显然s1已经帮他创建好了,它可以直接使用其引用。那么s1和s2所指向的都是同一个地址,所以s1==s2。
  • s3是一个字符串拼接操作,参与拼接的部分都是字面量,编译器会进行优化,在编译时s3就变成“Hello”了,所以s1==s3。
  • s4虽然也是拼接,但“lo”是通过new关键字创建的,在编译期无法知道它的地址,所以不能像s3一样优化。所以必须要等到运行时才能确定,必然新对象的地址和前面的不同。
  • 同理,s9由两个变量拼接,编译期也不知道他们的具体位置,不会做出优化。
  • s5是new出来的,在堆中的地址肯定和s4不同。
  • s6利用intern()方法得到了s5在字符串池的引用,并不是s5本身的地址。由于它们在字符串池的引用都指向同一个“Hello”对象,自然s1==s6。

4.String类的判断功能

String类的判断功能 含义
public boolean equals(Object obj) 比较字符串的内容是否相同,区分大小写
public boolean equalsIgnoreCase(String str) 比较字符串的内容是否相同,忽略大小写
public boolean contains(String str) 判断字符串中是否包含传递进来的字符串
public boolean startsWith(String str) 判断字符串是否以传递进来的字符串开头
public boolean endsWith(String str) 判断字符串是否以传递进来的字符串结尾
public boolean isEmpty() 判断字符串的内容是否为空串""
public class Demo6 {
    
    
    public static void main(String[] args) {
    
    
        //public boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
        boolean b = "ABC".equals("abc");
        System.out.println(b);     //false
        //public boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写
        boolean b1 = "ABC".equalsIgnoreCase("abc");
        System.out.println(b1);   //true
        //public boolean contains(String str):判断字符串中是否包含传递进来的字符串
        boolean b3 = "科比,我最爱的篮球明星".contains("篮球明星");
        System.out.println(b3);   //true
        //public boolean startsWith(String str):判断字符串是否以传递进来的字符串开头
        boolean b4 = "王者荣耀,我最爱玩的游戏".startsWith("王");
        System.out.println(b4);   //true
        //public boolean endsWith(String str):判断字符串是否以传递进来的字符串结尾
        boolean b5 = "最爱湖东行不足".endsWith("组");
        System.out.println(b5);   //false
        //public boolean isEmpty():判断字符串的内容是否为空串""。
        boolean b6 = "哈哈".isEmpty();
        System.out.println(b6);  //false

    }
}

模拟用户登录
案例演示: 需求:模拟登录,给三次机会,并提示还有几次。

import java.util.Scanner;
public class Demo1 {
    
    
    public static void main(String[] args) {
    
    
        //案例演示:    需求:模拟登录,给三次机会,并提示还有几次。
        String username = "张三";
        String passwd = "1234";

        for (int i = 0; i < 3; i++) {
    
    
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名:");
            String uname = scanner.nextLine();
            System.out.println("请输入密码为:");
            String pwd = scanner.nextLine();
            if (username.equals(uname) && passwd.equals(pwd)) {
    
    
                System.out.println("输入正确");
                break;
            } else {
    
    
                if (2 - i == 0) {
    
    
                    System.out.println("机会已用完,卡片锁住");
                } else {
    
    
                    System.out.println("输入错误,请重新输入");
                    System.out.println("还有" + (2 - i) + "次机会");
                }
            }

        }
    }
}

5.String类的获取功能

String类的获取功能 含义
public int length() 获取字符串的长度
public char charAt(int index) 获取指定索引位置的字符
public int indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引
public int indexOf(String str) 返回指定字符串在此字符串中第一次出现处的索引
public int indexOf(int ch,int fromIndex) 返回指定字符在此字符串中从指定位置后第一次出现处的索引
public int indexOf(String str,int fromIndex) 返回指定字符串在此字符串中从指定位置后第一次出现处的索引
public String substring(int start) 从指定位置开始截取字符串,默认到末尾
public String substring(int start,int end) 从指定位置开始到指定位置结束截取字符串
public class Demo2 {
    
    
    public static void main(String[] args) {
    
    
        //public int length():获取字符串的长度
        int length = "abc".length();
        System.out.println(length);   //3
        //public int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引
        String s="科比是我最喜欢的篮球明星";
        int index = s.indexOf('篮');
        System.out.println(index);    //8
        //public int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引
        int index1 = s.indexOf("篮球明星");
        System.out.println(index1);   //8
        //public int lastindexof(int ch):从后向前进行检索指定字符在此字符串中第一次出现处的索引
        int index2 = s.lastIndexOf('我');
        System.out.println(index2);   //3

    }
}
public class Demo3 {
    
    
    public static void main(String[] args) {
    
    
        //public char charAt(int index):获取指定索引位置的字符
        String s="易建联是中国现役最好的篮球运动员";
        //获取第一个字符
        char c = s.charAt(0);
        System.out.println(c);  //'易'
        //获取最后一个字符
        char c1 = s.charAt(s.length() - 1);
        System.out.println(c1); //'员'
    }
}
public class Demo4 {
    
    
    public static void main(String[] args) {
    
    
        String s="易建联是中国现役最好的篮球运动员";
        //public String substring(int start):从指定位置开始截取字符串,默认到末尾
        String s1 = s.substring(4);
        System.out.println(s1);  //从索引4处(包含索引4)对字符串进行截取
        //public String substring(int start,int end):从指定位置开始到指定位置结束截取字符串
        String s2 = s.substring(0, 3);    //含头不含尾进行截取字符串
        System.out.println(s2);    //易建联
    }
}

6.字符串的遍历

public class Demo5 {
    
    
    public static void main(String[] args) {
    
    
        String s="易建联是中国现役最好的篮球运动员";
        //正向遍历
        for (int i = 0; i < s.length(); i++) {
    
    
            char c = s.charAt(i);
            System.out.println(c);
        }
        System.out.println("=================");
        //反向遍历
        for (int i1 = s.length()-1; i1 >= 0; i1--) {
    
    
            char c1 = s.charAt(i1);
            System.out.println(c1);
        }
    }
}

案例练习: 统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)

import java.util.Scanner;
public class Demo6 {
    
    
    public static void main(String[] args) {
    
    
        //案例练习: 统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String s = sc.nextLine();
        int samllnum=0;
        int bignum=0;
        int dignum=0;
        for (int i = 0; i < s.length(); i++) {
    
    
            char c = s.charAt(i);
            if(c>='a'&&c<='z'){
    
    
                samllnum++;
            }
            else if(c>='A'&&c<='Z'){
    
    
                bignum++;
            }
            else if(c>='0'&&c<='9'){
    
    
                dignum++;
            }
        }
        System.out.println("小写字母字符为:"+samllnum+"个");
        System.out.println("大写字母字符为:"+bignum+"个");
        System.out.println("数字字符为:"+dignum+"个");
    }

}

7.String类的转换功能

String类的转换功能 含义
public byte[] getBytes() 把字符串转换为字节数组
public char[] toCharArray() 把字符串转换为字符数组
public static String valueOf(char[] chs) 把字符数组转成字符串
public static String valueOf(int i) 把int类型的数据转成字符串
public String toLowerCase() 把字符串转成小写
public String toUpperCase() 把字符串转成大写
public String concat(String str) 把字符串拼接
public class Demo1 {
    
    
    public static void main(String[] args) {
    
    
        //public byte[] getBytes():把字符串转换为字节数组
        String s="abc";
        byte[] bytes = s.getBytes();
        for (int i = 0; i < bytes.length; i++) {
    
    
            byte aByte = bytes[i];
            System.out.println(aByte); //97 98 99
        }
        System.out.println("===============");
        //public char[] toCharArray():把字符串转换为字符数组
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
    
    
            char aChar = chars[i];
            System.out.println(aChar);  //a b c
        }
    }
}
public class Demo2 {
    
    
    public static void main(String[] args) {
    
    
        //public static String valueOf(char[] chs):把字符数组转成字符串
        char[] chars = new char[]{
    
    '我','爱','你'};
        String s = String.valueOf(chars);
        System.out.println(s);
        System.out.println("=============");
        //public static String valueOf(int i):把int类型的数据转成字符串
        int i=123456;
        String s1 = String.valueOf(i);
        System.out.println(s1);
    }
}
public class Demo3 {
    
    
    public static void main(String[] args) {
    
    
        //public String toLowerCase():把字符串转成小写
        String s="SDDD";
        String s1 = s.toLowerCase();
        System.out.println(s1);

        System.out.println("========");
        //public String toUpperCase():把字符串转成大写
        String s2="sdsdd";
        String s3 = s2.toUpperCase();
        System.out.println(s3);

        System.out.println("==========");
        //public String concat(String str):把字符串拼接
        String s4="kobe";
        String s5 = s4.concat("bryant");
        System.out.println(s5);
    }
}

案例演示:把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符)

public class Demo4 {
    
    
    public static void main(String[] args) {
    
    
        //案例演示:把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符)
        String s="asSADFDDFLLasddfx";
        String s1 = s.substring(0, 1).toUpperCase().concat(s.substring(1).toLowerCase());
        System.out.println(s1); //Assadfddfllasddfx
    }
}

8. String类的其它功能

8.1 String的替换功能

语法 含义
public String replace(char old,char new) 将指定字符进行互换
public String replace(String old,String new) 将指定字符串进行互换
ublic class Demo5 {
    
    
    public static void main(String[] args) {
    
    
        /*String类的特有功能:String类的替换功能*/
        /*public String replace(char old,char new)
           将指定字符进行替换
         */
        String s="人人都是平等的,不能进行种族歧视";
        String s1 = s.replace('种', '#');
        System.out.println(s1);
        /*public String replace(String old,String new)
          将制定的字符串进行替换
         */
        String s2 = s.replace("种族歧视", "****");
        System.out.println(s2);

    }
}

输出结果为:在这里插入图片描述


8.2 String类去除字符串两端空格的功能

语法 含义
public String trim() 去除两端空格
public class Demo6 {
    
    
    public static void main(String[] args) {
    
    
        //public String trim():去除两端空格
        String s="   她来听我的演唱会   ";
        String trim = s.trim();
        System.out.println(trim);

    }
}

8.3 String的按字典顺序比较两个字符串

语法 含义
public int compareTo(String str) 会对照ASCII 码表 ,从第一个字母进行减法运算 ,返回的就是这个减法的结果。如果前面几个字母一样会根据两个字符串的长度进行减法运算返回的就是这个减法的结果, 如果连个字符串一摸一样 返回的就是0。
public int compareToIgnoreCase(String str) 跟上面一样 只是忽略大小写的比较
public class Demo7 {
    
    
    public static void main(String[] args) {
    
    
        //String类的比较字符串功能
        /*public int compareTo(String str) 会对照ASCII 码表
        从第一个字母进行减法运算 返回的就是这个减法的结果
        如果前面几个字母一样会根据两个字符串的长度进行减法运算返回的就是这个减法的结果
      如果连个字符串一模一样 返回的就是0
         */
        int i = "abc".compareTo("abc");
        System.out.println(i);  //0
        int i1 = "abc".compareTo("bbc");
        System.out.println(i1);  //-1
        int i2 = "abc".compareTo("abd");
        System.out.println(i2);  //-1
        int i3="abc".compareTo("abcde");
        System.out.println(i3);   //-2
        /*public int compareToIgnoreCase(String str) 跟上面一样 只是忽略大小写的比较 */
        int i4 = "abc".compareToIgnoreCase("ABC");
        System.out.println(i4);   //0
    }
}

9.把数组转成字符串

案例:需求:把数组中的数据按照指定个格式拼接成一个字符串
举例: int[] arr = {1,2,3}; 拼接结果: “[1, 2, 3]”

public class Demo8 {
    
    
    public static void main(String[] args) {
    
    
      /* 需求:把数组中的数据按照指定个格式拼接成一个字符串
        举例:
        int[] arr = {1,2,3};
        拼接结果:
        "[1, 2, 3]"
        */

        int [] arr={
    
    1,2,3};
        String s="[";
        for (int i = 0; i < arr.length; i++) {
    
    
            if(i==arr.length-1){
    
    
                s+=arr[i]+"]";
            }
            else{
    
    
              s+=arr[i]+",";
            }

        }
        System.out.println(s);
    }
}

10.字符串反转操作

案例:
需求:把字符串反转,举例:键盘录入"abc" ,反转结果:“cba”

import java.util.Scanner;
public class Demo9 {
    
    
    public static void main(String[] args) {
    
    
       /* 案例:
        需求:把字符串反转,举例:键盘录入"abc"  ,反转结果:"cba"
        */
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入字符串:");
        String s = sc.nextLine();
        String s1="";
        for (int i = s.length()-1; i >=0; i--) {
    
    
            char c = s.charAt(i);
            s1+=c;

        }
        System.out.println(s1);
    }
}

输出的结果为:
在这里插入图片描述


11.在大串中查找小串出现的次数

需求:统计大串中小串出现的次数
举例: “woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun” 中java出现了5次

public class Demo10 {
    
    
    public static void main(String[] args) {
    
    
        /*需求:统计大串中小串出现的次数
        举例: "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun"
         */
        String s= "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
        int count=0;
        String s1 = s.replace("java", "*");
        for (int i = 0; i < s1.length(); i++) {
    
    
            if(s1.charAt(i)=='*'){
    
    
                count++;
            }
        }
        System.out.println("Java小串出现了"+count+"次");
    }
}

输出的结果为:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41537102/article/details/111475584
今日推荐