栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【迷人的爪哇】——Java-String类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【迷人的爪哇】——Java-String类

目录

一、介绍String类

二、String的使用

2.1 字符串的构造

 2.2 String对象的比较

1、 == 比较

 2、boolean equals(Object  anObject)方法

 3、int compareTo(String s)方法

2.3 字符串的查找

1、char charAt(int index)

 2、int indexOf(int ch)

 3、in lastIndexOf(int ch)

 2.4 字符串转换

1、数值和字符串的转换(valueOf( ))

​编辑

 2、大小写转换

3、字符串变成数组

 4、格式化转换

 2.5 字符串的替换

 2.6 字符串的拆分

1、字符串拆分部分和全部

2.7 字符串的截取

 ​编辑

2.8 其它操作方法

 2.9 字符串常量池

1、字符串常量池(StringTable)

2、intern方法

2.10字符串的不可变性

2.11 字符串的修改

三、StringBulider和StringBuffer

3.2 面试题:

1、String、StringBuffer、StringBuilder的区别

2、以下总共创建多少个对象【不考虑常量池提前存在】


一、介绍String类

String类是字符串类型,是Java语言专门提供的。

二、String的使用

2.1 字符串的构造

String类的构造方法有以下三种:

public class Test1 {
    public static void main(String[] args) {

        String str1 = "Hello";

        String str2 = new String("hi");

        char[] chars = {'a','b','c'};
        String str3 = new String(chars);
    }
}

当我们调试一下的时候,就可以发现String类的引用的组成:

 当我们画图来表示它们的内存分布:

获取字符串的长度:

public class Test {
    public static void main(String[] args) {
        String str = "hello";、

        System.out.println(str.length());
    }
}

 

注:

求字符串长度使用了.length()方法,而求数组长度时,使用数组名.length。

 2.2 String对象的比较

1、 == 比较

比较的是变量中的值,对于引用类型比较的就是地址:

public class Test {

    public static void main(String[] args) {
        String str1 = new String("hello");
        String str2 = new String("hello");

        System.out.println(str1 == str2);
    }
}
 

 2、boolean equals(Object  anObject)方法

按字典序(字符大小的顺序)比较:

public class Test {

    public static void main(String[] args) {
        String str1 = new String("hello");
        String str2 = new String("hello");

        System.out.println(str1.equals(str2));
    }
}

 3、int compareTo(String s)方法

按照字典序排序,返回的是int类型,有以下两种比较方式:

  1. 返回两个不等字符的ASCII值的差值。
  2. 返回两个字符串长度的差值。
public class Test {

    public static void main(String[] args) {
        String str1 = new String("helloe");
        String str2 = new String("hello");

        System.out.println(str1.compareTo(str2));

    }
}

注:

  1. Java中的字符串没有所谓的 '' 结尾。
  2. equals比较和compareTo比较都有忽略大小写的比较:equalsIgnoreCase()、compareToIgnoreCase()。 

2.3 字符串的查找

1、char charAt(int index)

功能:返回index位置上的字符,如果index为负数或越界,抛出IndexOutOfBoundsException异常。

public class Test {

    public static void main(String[] args) {
        String str = "hello";
        for (int i = 0; i < str.length(); i++) {
            char s1 = str.charAt(i);
            System.out.println(s1);
        }

    }
}

 2、int indexOf(int ch)

功能:返回ch第一次出现的位置的下标,没有返回-1

public class Test {

    public static void main(String[] args) {
        String str = "hello";
        int index = str.indexOf('l');
        System.out.println(index);
    }
}


 还有带有两个参数的indexOf(int ch,fromIndex)

从fromIndex位置开始找 ch第一次出现的位置的下标,没有就返回-1

public class Test {

    public static void main(String[] args) {
        String str = "hello";
        int index = str.indexOf('e',3);
        System.out.println(index);
    }
}


找一个子串在字符串中第一次出现的位置 int indintexOf  ch(String  str):

public class Test {

    public static void main(String[] args) {
        String str = "hello";
        int index = str.indexOf("ll");
        System.out.println(index);
    }
}

 3、in lastIndexOf(int ch)

功能:从后往前找,返回ch第一次出现的位置,没有返回-1

public class Test {

    public static void main(String[] args) {
        String str1 = "abab.cde";
        int index = str1.lastIndexOf('.');
        System.out.println(index);
    }
}


带有两个参数的in lastIndexOf(int ch,int fromindex):

从fromindex位置开始找,从后往前找ch第一次出现的位置,没有返回-1

public class Test {

    public static void main(String[] args) {
        String str1 = "abab.cde";
        int index = str1.lastIndexOf('c',6);
        System.out.println(index);
    }
}


从后往前找子串在字符串中第一次出现的位置in lastIndexOf(String str):

public class Test {

    public static void main(String[] args) {
        String str1 = "abab.cde";
        int index = str1.lastIndexOf("ba");
        System.out.println(index);
    }
}


从fromindex位置开始找,从后往前找str第一次出现的位置,没有返回-1;

 in lastIndexOf(int ch,int fromindex):

public class Test {

    public static void main(String[] args) {
        String str1 = "ababa.cde";
        int index = str1.lastIndexOf("ba",6);
        System.out.println(index);
    }
}

 2.4 字符串转换

1、数值和字符串的转换(valueOf( ))

其方法重载如下:

  


数字转字符串、字符串转数字:

public class Test {

       public static void main(String[] args) {
        String s1 = String.valueOf(123);
        String s2 = String.valueOf(1.11);
        int a = Integer.parseInt("123");

        System.out.println(a);
        System.out.println(s1);
        System.out.println(s2);

    }

}


把其他数据类型转换成字符串:

class Student{
    public int Age;
    public Student(int age) {
        Age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "Age='" + Age + ''' +
                '}';
    }
}
public class Test {

    public static void main(String[] args) {

        String s3 = String.valueOf(new Student(18));
        System.out.println(s3);
      
    }

 进制转换:

public class Test {

    public static void main(String[] args) {

        int a = Integer.valueOf("64",8);
        System.out.println(a);
        
    }
}

 2、大小写转换
public class Test {

    public static void main(String[] args) {
        String s1 = "hello";
        String ret = s1.toUpperCase();
        System.out.println(ret);
        System.out.println("s1: "+s1);

        String s2 = "HELLO";
        String ret2 = s2.toLowerCase();
        System.out.println(ret2);
        System.out.println("s2: "+s2);
    }
}

 注:转换大小写不会改变原来的字符串,而是重新实例化一个字符串。

3、字符串变成数组
public class Test {

    public static void main(String[] args) {
        String s1 = "hello";
        char[] chars = s1.toCharArray();
        for(char x: chars){
            System.out.println(x);
        }
    }
}

 4、格式化转换
public class Test {

    public static void main(String[] args) {
        String  s = String.format("%d-%d-%d",2019,9,14);
        System.out.println(s);
    }
}

 2.5 字符串的替换
public class Test {

    public static void main(String[] args) {
        String s1 = "abcdefg";
        String ret = s1.replace("bc","ww");
        System.out.println(ret);

        System.out.println("s1: "+s1);
    }
}

 2.6 字符串的拆分

1、字符串拆分部分和全部
 public static void main(String[] args) {
        String s1 = "I Love You";
        String[] ret = s1.split(" ",2);//控制分几组
        for(String x: ret){
            System.out.println(x);
        }
        String[] ret1 = s1.split(" ");
        for(String x: ret1){
            System.out.println(x);
        }
    }
}

 注:

  1. 字符要注意转移字符,在前面加  \
  2. 如果是  ' ',要写成 ' \\ '。
  3. ' | '可以作为多个字符的连字符。

例(多次拆分):

public class Test {

    public static void main(String[] args) {
        String str = "name=lisi&age=20";
        String[] ret = str.split("&");
        for(String s : ret){
            String[] ss = s.split("=");
            for (String x : ss){
                System.out.println(x);
            }
            System.out.println();
        }
    }
}

2.7 字符串的截取
public class Test {

    public static void main(String[] args) {
        String str = "abcdef";
        String ret = str.substring(1,4);   
        System.out.println(ret);

        String ret1 = str.substring(1);
        System.out.println(ret1);
    }
}

 

 注:

substring()它的范围是左闭右开的[  )。

2.8 其它操作方法

去掉字符串左右空格:

public class Test {

    public static void main(String[] args) {
        String str = "   abcd ef   ";
        String ret = str.trim();
        System.out.println(ret);
    }

}

 2.9 字符串常量池

思考下面程序的运行结果:

 由结果可以看出来,s1和s2引用的是同一个对象,而s3和s4却不是,这是因为:

在Java中有很多经常使用的字面常量,为了程序的运行速度更快、更省内存,Java为8种数据类型和String类提供了常量池:

  1. Class文件常量池:Java源文件编译后生成.class文件
  2. 运行时常量池:在.Class文件被加载时,.Class文件中的常量池被加载到内存中称为运行时常量池,运行时常量池每个类都有一份
  3. 字符串常量池。

1、字符串常量池(StringTable)

上面代码中,双引号引起来的字符串,都会存在常量池当中。

当第二次存储这个字符串的时候,都会去常量池检查是否存在,有就返回,没有就创建。

2、intern方法

 检查s1所指向的对象在常量池当中是否存在,不存在,就把当前对象入池。存在则返回常量池的对象。

  •  面试题:请解释String类中两种实例化的区别

1、String str = "hello"

    只会开辟一块内存空间,保存在字符串常量池中,然后str共享常量池中的String对象。

2、String str = new String("hello")

     会开辟两块堆内存空间,字符串"hello"保存在字符串常量池中,然后常量池中的String        对象给新开辟的String对象赋值。

 

3、String str = new String(new char[]{'h', 'e', 'l', 'l', 'o'})
     现在堆上创建一个String对象,然后利用copyof将重新开辟数组空间,将参数字符串数       组中内容拷贝到String对象中。

2.10字符串的不可变性

 value被private修饰,所以类外拿不到这个变量,所以字符串不能修改的(value的指向不能变,而可以通过value[0] = 'p' 来修改值),与被final修饰没有关系。

2.11 字符串的修改
 public static void main(String[] args) {
        String s = "hello";
        s += " world";
        System.out.println(s); // 输出:hello world
    }

当我们观察它的汇编代码就可以发现:

实现:

public class Test1 {
    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("hello");
        stringBuilder.append(" world");
        String s = stringBuilder.toString();

        System.out.println(s);
    }
}

 因为String类是不能修改的,所有的修改都会创建新对象,效率非常低下。

三、StringBulider和StringBuffer

在Java中,为了方便字符串的修改,提供StringBulider和StringBuffer类,这两个类大部分都是相同的。

 注:

  1. String和StringBuilder类不能直接转换,可以借助方法。
  2. String转换成StringBuilder:利用StringBuilder的构造方法或append()方法。
  3. StringBuilder变为String:调用toString()方法。

3.2 面试题:

1、String、StringBuffer、StringBuilder的区别
  1. String的内容不可修改,StringBuffer与StringBuilder的内容可以修改.
  2. StringBuffer与StringBuilder大部分功能是相似的
  3. StringBuffer采用同步处理,属于线程安全操作;而StringBuilder未采用同步处理,属于线程不安全操作

2、以下总共创建多少个对象【不考虑常量池提前存在】
String str1 = new String("ab"); 
String str2 = new String("a") + new String("b");

解析:

  1. str1创建两个对象,第一个new String()堆中的对象,第二个"ab"常量池的对象。
  2. str2创建六个对象,前四个分别是new String()堆中的对象,'a'常量池的对象,new String()堆中的对象,'b'常量池的对象,使用  +  拼接字符时,会创建第五个StringBuilder对象,然后StringBuilder转换成String时调用toString方法又会创建一个String类的对象。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/939403.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号