String类

2024-07-01 1118阅读

学习String类,主要就是学习String类中包含的一些方法。

一、String类中的常用方法:

1. String类的定义方法:

1. String s1 = "Hello";

2. String s2 = new String("Hello");

3. char[] array = {'h', 'e', 'l', 'l', 'o'};

    String s3 = new String(array); 

注意:第一类构造方法和其他两类有所差异,s1会先去检查字符串常量池中有没有,没有的话才会创建一个abc的对象,举个例子:

public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "abc";
        System.out.println(s1 == s2);
    }

运行结果:

true

2. String对象的比较:

2.1 "=="比较:

“==”比较的是引用中的地址,判断引用的是否是同一个对象。

public static void main(String[] args) {
        String s1 = "abc";
        String s2 = new String("abc");
        String s3 = s1;
        System.out.println(s1 == s2);//false
        System.out.println(s1 == s3);//ture
    }

运行结果: 

false
true

2.2 boolean equals(Object anObject) 方法: 

equals方法是用来比较引用对象是否相同的方法。

public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "def";
        String s3 = new String("abc");
        System.out.println(s1.equals(s2));//false
        System.out.println(s1.equals(s3));//true
    }

运行结果:

false
true

2.3 int compareTo(String s) 方法: 

compareTo方法用来比较字符串大小,从零下标开始对字符依次进行比较,当两个字符不同或到达字符串末尾,返回差值。

public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "acc";
        System.out.println(s1.compareTo(s2));
    }

运行结果:

-1

2.4 int compareToIgnoreCase(String str) 方法:

与compareTo比较方式相同,只不过会忽略字符的大小写。

public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "ABC";
        System.out.println(s1.compareToIgnoreCase(s2));
    }

运行结果: 

0

3. 字符串查找:

3.1 charAt方法:

char charAt(int index):

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

public static void main(String[] args) {
        String s = "abcdef";
        char ch = s.charAt(2);
        System.out.println(ch);
    }

 运行结果:

c

3.2 int indexOf(int ch):

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

public static void main(String[] args) {
        String s = "abcdef";
        int pos = s.indexOf('d');
        System.out.println(pos);
    }

运行结果:

3

3.3 int indexOf(int ch, int fromIndex):

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

public static void main(String[] args) {
        String s = "abcdef";
        int pos = s.indexOf('d', 4);
        System.out.println(pos);
    }

运行结果:

-1

3.4 int indexOf(String str):

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

public static void main(String[] args) {
        String s = "abcdef";
        int pos = s.indexOf("bc");
        System.out.println(pos);
    }

运行结果:

1

3.5 int indexOf(String str, int fromIndex):

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

public static void main(String[] args) {
        String s = "abcdef";
        int pos = s.indexOf("bc", 2);
        System.out.println(pos);
    }

运行结果:

-1

3.6 int lastIndexOf(int ch):

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

public static void main(String[] args) {
        String s = "abcdef";
        int pos = s.lastIndexOf('d');
        System.out.println(pos);
    }

运行结果:

3

3.7 int lastIndexOf(int ch, int fromIndex):

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

public static void main(String[] args) {
        String s = "abcdef";
        int pos = s.lastIndexOf('d', 2);
        System.out.println(pos);
    }

运行结果:

-1

3.8 int lastIndexOf(String str):

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

public static void main(String[] args) {
        String s = "abcdef";
        int pos = s.lastIndexOf("cd");
        System.out.println(pos);
    }

运行结果:

2

 3.9 int lastIndexOf(String str, int fromIndex):

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

public static void main(String[] args) {
        String s = "abcdef";
        int pos = s.lastIndexOf("cd", 1);
        System.out.println(pos);
    }

运行结果:

-1

4. 转化:

4.1 数值和字符串转化:

valueOf()方法:

public static void main(String[] args) {
        String s1 = String.valueOf(1234);
        String s2 = String.valueOf(12.34);
        String s3 = String.valueOf(true);
        String s4 = String.valueOf(new Student("wyh", 12));
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
    }
1234
12.34
true
Student{name='wyh', age=12}

4.2 字 符 串 转 数 组:

toCharArray()方法:

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

运行结果:

[h, e, l, l, o]

 4.3 大 小 写 转 换:

toUpperCase()和toLowerCase()方法:
public static void main(String[] args) {
        String s = "hello";
        String s1 = s.toUpperCase();
        System.out.println(s1);
        String s2 = s1.toLowerCase();
        System.out.println(s2);
    }

运行结果:

HELLO
hello

4.4 格 式 化:

format()方法:
public static void main(String[] args) {
        int year = 2024;
        int month = 6;
        int day = 29;
        String s = String.format("%02d-%02d-%02d", year, month, day);
        System.out.println(s);
    }

运行结果:

2024-06-29

5. 字 符 串 替 换:

5.1 String replaceAll(String regex, String replacement):

替换所有的指定内容。

public static void main(String[] args) {
        String s = "abcdefg";
        String s1 = s.replaceAll("c", "cc");
        System.out.println(s1);
    }

运行结果:

abccdefg

5.2 String replaceFirst(String regex, String replacement):

替换首个内容。

public static void main(String[] args) {
        String s = "abcdecfg";
        String s1 = s.replaceFirst("c", "cc");
        System.out.println(s1);
    }

运行结果:

abccdecfg

6. 字符串拆分:

6.1 String[] split(String regex):

将字符串全部拆分,用字符串数组接受。

public static void main(String[] args) {
        String s1 = "hello-world";
        System.out.println(Arrays.toString(s1.split("-")));
    }

运行结果:

[hello, world]

6.2 String[] split(String regex, int limit):

将字符串以指定的格式,拆分为limit组。

public static void main(String[] args) {
        String s1 = "he-llo-wor-ld";
        System.out.println(Arrays.toString(s1.split("-", 3)));
    }

运行结果:

[he, llo, wor-ld]

有些特殊字符作为分割符可能无法正确切分, 需要加上转义。(转义字符为“\\”)

例1. 

public static void main(String[] args) {
        String s1 = "he.llo.wor.ld";
        System.out.println(Arrays.toString(s1.split("\\.")));
    }

运行结果:

[he, llo, wor, ld]

例2. 

public static void main(String[] args) {
        String s1 = "he\\llo\\wor\\ld";
        System.out.println(Arrays.toString(s1.split("\\\\")));
    }

运行结果:

[he, llo, wor, ld]

补充: 

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

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

3. 如果一个字符串中有多个分隔符,可以用"|"作为连字符.

public static void main(String[] args) {
        String s1 = "he&llo=wor.ld";
        System.out.println(Arrays.toString(s1.split("&|=|\\.")));
    }

运行结果:

[he, llo, wor, ld]

7. 字符串截取:

从一个完整的字符串之中截取出部分内容。

7.1 String substring(int beginIndex):

从指定索引截取到结尾。

public static void main(String[] args) {
        String s = "abcdefghi";
        System.out.println(s.substring(3));
    }

运行结果:

defghi

7.2 String substring(int beginIndex, int endIndex):

截取部分内容(左闭右开)。

public static void main(String[] args) {
        String s = "abcdefghi";
        System.out.println(s.substring(3, 6));
    }

运行结果:

def

8. 其他操作方法:

去掉字符串中的左右空格,保留中间空格。

public static void main(String[] args) {
        String s = " a b c ";
        System.out.println(s.trim());
    }

运行结果:

a b c

二、String的不可变性:

在演示上面所有的String类的方法时,其实都不是对字符串本身进行修改,都是创建了一个新的对象。

当我们点进String这个类时会发现:

String类

这里面的private就是它为什么具有不可变性的原因了,我们没有修改这个成员变量的权限。 

如果每次修改字符串都需要创建一个新的对象,效率会大大降低,所以我们在使用String的时候应该尽量避免对字符串的修改。

三、StringBuilder和StringBuffer:

运行一段代码:

public static void main(String[] args) {
        long start = System.currentTimeMillis();//获得程序开始的时间
        String s1 = "";
        for (int i = 0; i  

运行结果:

62
1
1

观察发现,当使用StringBuilder和StringBuffer时字符串的拼接效率会更快,这是因为StringBuilder和StringBuffer在拼接字符串的时候不需要创建新的对象,直接就是在字符串本身进行修改。

StringBuilder和StringBuffer之间的差别:

StringBuilder是单线程,StringBuffer是多线程,可以保证线程安全,但不意味着StringBuffer一定比StringBuilder好,因为在单线程情况下使用StringBuffer也是对资源的一种浪费。

VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]