JavaSE——String类常用方法详解(玩转字符串)

ced485cbb11e458d81a746890b32cf3f.gif

作者:敲代码の流川枫

博客主页:流川枫的博客

专栏:和我一起学java

语录:Stay hungry stay foolish

工欲善其事必先利其器,给大家介绍一款超牛的斩获大厂offer利器——牛客网

点击免费注册和我一起刷题吧  

文章目录

1. 字符串的常用构造

2. String对象的比较

1. ==比较是否引用同一个对象

2. boolean equals(Object anObject)方法:按照字典序比较

3. int compareTo(String s)方法: 按照字典序进行比较

4. int compareToIgnoreCase(String str)方法

3. 字符串查找

char charAt(int index)

int indexOf(int ch)

int indexOf(int ch, int fromIndex)

int indexOf(String str)

int indexOf(String str, int fromIndex)

int lastIndexOf(int ch)

int lastIndexOf(int ch, int fromIndex)

int lastIndexOf(String str)

int lastIndexOf(String str, int fromIndex)

4. 转化

1. 数值和字符串转化

2. 大小写转换

3. 字符串转数组 

4. 格式化

5. 字符串替换

 1.替换所有的指定内容

2.替换首个内容

6. 字符串拆分

1.字符串全部拆分 

2.字符串以指定的格式,拆分为limit组

3. “.”分割

7. 字符串截取

1.从指定索引截取到结尾

2.截取部分内容

8. String trim()


1. 字符串的常用构造

1.使用常量构造

2.使用newString构造

3.使用字符数组构造

public class Test {
    public static void main(String[] args) {
        //1
        String str1 = "hello";
        System.out.println(str1);
        //2
        String str2 = new String("hello");
        System.out.println(str2);
        //3
        char[] chars = {'h','e','l','l','o'};
        System.out.println(chars);
    }
}

 其它方法使用时参考:字符串官方文档 

字符串是不能被继承的,下面是String类源码

 value是一个char类型数组,字符串实际存储在char类型的数组中,且字符串结尾没有/0

  因此String是引用类型,内部并不存储字符串本身,看一个例子:

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

        String str1 = new String("hello");

        String str2 = new String("world");

        String str3 = str1;
        System.out.println(str3);
    }
}

str1和str2引用的是不同对象str1和str3引用的是同一对象 

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

        String str1 = new String("hello");

        String str2 = new String("hello");
        
        System.out.println(str1==str2);

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

    }
}

 因为String类是引用类型,所以就算字符串内容一样,它们也不相等,要想比较它们是否相等,要通过对象调用方法来比较

在Java中,""引起来的也是String类的对象

public class Test {
    public static void main(String[] args) {
        System.out.println("hello".toString());

    }
}

可以调用toString()等方法 

2. String对象的比较

1. ==比较是否引用同一个对象

对于基本类型变量,比较的是两个变量中存储的值是否相同

对于引用类型变量,比较的是两个引用变量引用的是否为同一个对象

如上文提到的

2. boolean equals(Object anObject)方法:按照字典序比较

字典序:字符大小的顺序

 String类重写了父类Object中equals方法,Object中equals默认按照==比较

重写之后的比较逻辑:

 public boolean equals(Object anObject) {

        //1. 先检测this和anObject是否为同一个对象比较,如果是返回true

        if (this == anObject) {
            return true;
        }

        //2. 检测anObject是否为String类型的对象,如果是继续比较,否则返回false

        if (anObject instanceof String) {

            //向下转型

            String anotherString = (String)anObject;
            int n = value.length;

        //3. this和anObject两个字符串的长度是否相同,是继续比较,否则返回false

            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;

                //4. 按照字典序,从前往后逐个字符进行比较

                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

3. int compareTo(String s)方法: 按照字典序进行比较

equals返回的是boolean类型,而compareTo返回的是int类型

比较方式:

1. 先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值

2. 如果前k个字符相等(k为两个字符长度最小值),返回值两个字符串长度差值

看一个例子: 

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

        String str1 = new String("hello");

        String str2 = new String("hello");

        int ret = str1.compareTo(str2);
        if(ret>0){
            System.out.println("str1>str2");
        } else if (ret==0) {
            System.out.println("str1=str2");
        }
        else {
            System.out.println("str1<str2");
        }

    }

}

 源码:

public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }

4. int compareToIgnoreCase(String str)方法

与compareTo方式相同,但是忽略大小写比较 

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

        String s1 = new String("abc");
        String s2 = new String("ac");
        String s3 = new String("ABc");
        String s4 = new String("abcdef");
        System.out.println(s1.compareToIgnoreCase(s2)); //不同输出字符差值-1
        System.out.println(s1.compareToIgnoreCase(s3)); //相同输出0
        System.out.println(s1.compareToIgnoreCase(s4)); //前k个字符完全相同,输出长度差值-3
        
    }
}

3. 字符串查找

String类提供的常用查找的方法:

char charAt(int index)

返回index位置上字符,如果index为负数或者越界,抛出IndexOutOfBoundsException异常

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

 int indexOf(int ch)

返回ch第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdef");

        System.out.println(s1.indexOf('c'));
    }
}

int indexOf(int ch, int fromIndex)

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

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.indexOf('c',3));
    }
}

int indexOf(String str)

返回str第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.indexOf("cde"));
    }
}

int indexOf(String str, int fromIndex)

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

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.indexOf("cde",3));
    }
}

int lastIndexOf(int ch)

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

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("c"));
    }
}

int lastIndexOf(int ch, int fromIndex)

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

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("c",4));
    }
}

int lastIndexOf(String str)

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

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("abc"));
    }
}

int lastIndexOf(String str, int fromIndex)

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

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("abc",4));
    }
}

4. 转化

1. 数值和字符串转化

public class Test {
    public static void main(String[] args) {
        String s1 = String.valueOf(123);

        System.out.println(s1);
    }
}

 

 可以看到有很多重载的方法供我们使用,可以将很多不同类型的数值转换为字符串

2. 大小写转换

toUpperCase()

toLowerCase()

public class Test {
    public static void main(String[] args) {
        String s1 = "hellO嗨";
        String ret = s1.toUpperCase();
        System.out.println(ret);
    }
}

toUpperCase() 只会将小写转换成大写,其它都不变,toLowerCase()也是如此

3. 字符串转数组 

toCharArray()

public class Test {
    public static void main(String[] args) {
        String str1 = "abcdef";
        char[] chars = str1.toCharArray();
        System.out.println(Arrays.toString(chars));
    }
}

 数组转字符串

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

        char[] chars = {'h','e','l','l','o'};
        String s1 = new String(chars);
        System.out.println(s1);
    }
}

4. 格式化

String.format()

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

        String s = String.format("%d-%d-%d",2022,8,14);
        System.out.println(s);
    }
}

5. 字符串替换

注意事项: 由于字符串是不可变对象, 替换不修改当前字符串, 而是产生一个新的字符串

使用一个的字符串替换已有的字符串数据,方法:

1.String replaceAll(String regex, String replacement) 

2.String replaceFirst(String regex, String replacement)

 1.替换所有的指定内容

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

        String s = "abcadeafagf";
        String ret = s.replaceAll("a","c");
        System.out.println(s);
        System.out.println(ret);
    }
}

 

 可以看出替换字符串后原字符串是不变的,替换后需要一个新的字符串接收

2.替换首个内容


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

        String s = "abcadeafagf";
        String ret = s.replaceFirst("a","c");
        System.out.println(s);
        System.out.println(ret);
    }
}

6. 字符串拆分

将一个完整的字符串按照指定的分隔符划分为若干个子字符串

String[] split(String regex)

String[] split(String regex, int limit)

1.字符串全部拆分 

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

        String s = "hello world hello";
        String[] ret = s.split(" ");
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

2.字符串以指定的格式,拆分为limit组

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

        String s = "hello world hello";
        String[] ret = s.split(" ",2);
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

3. “.”分割

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

        String s = "hello.world.hello";
        String[] ret = s.split(".");
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

 正常使用split(".")进行分割,我们发现打印数组是空的,说明没有分割成功

原因:"."需要转义,添加"\\."后,可以分割

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

        String s = "hello.world.hello";
        String[] ret = s.split("\\.");
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

总结:

1. 字符"|","*","+"都得加上转义字符,前面加上"\\"

2. 而如果是"\",那么就得写成"\\\\"

3. 如果一个字符串中有多个分隔符,可以用"|"作为连字符,即s.split("=|&");是通过=和&分割s字符串

7. 字符串截取

String substring(int beginIndex)

String substring(int beginIndex, int endIndex)

1.从指定索引截取到结尾

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

        String s = "hello world";
        String ret = s.substring(5);
        System.out.println(s);
        System.out.println(ret);
    }
}

2.截取部分内容

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

        String s = "hello world";
        String ret = s.substring(0,5);
        System.out.println(s);
        System.out.println(ret);
    }
}

 总结:

1. 索引从0开始

2. 注意前闭后开区间的写法, substring(0, 5) 表示包含 0 号下标的字符, 不包含 5 号下标

8. String trim()

功能:去掉字符串中的左右空格,保留中间空格

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

        String s = "   hello world    ";
        String ret = s.trim();
        System.out.println(s);
        System.out.println(ret);
    }
}

 总结:

我们注意到,大多数的String类方法都不是直接操作原字符串,都会返回一个新的字符串

“ 本期的分享就到这里了, 记得给博主一个三连哈,你的支持是我创作的最大动力!

ced485cbb11e458d81a746890b32cf3f.gif

猜你喜欢

转载自blog.csdn.net/chenchenchencl/article/details/126330055
今日推荐