JavaSE String类

1. 概念

String类是一种引用数据类型,一般用于字符串的构建

2. String类常用方法

2.1 字符串构建

String类提供的构造方法非常的,常用的为以下三种:

  1. 使用常量串构造

    String s1 = "hello world";
    System.out.println(s1);
    
  2. 直接new String对象

    String s2 = new String("hello world");
    System.out.println(s2);
    
  3. 使用字符数组进行构造

    char[] array = {'h','e','l','l','o','w','o','r','l','d'};
    String s3 = new String(array);
    System.out.println(s3);
    

注:

  • String是引用类型,内部并不存储字符串本身,在String类的实现源码中,String类实例变量如下:

    在这里插入图片描述

    package demo1;
    
    public class Test1 {
        public static void main(String[] args) {
            //s1和s2引用的是不同对象,s1和s3引用的是同一个对象
            String s1 = new String("hello");
            String s2 = new String("world");
            String s3 = s1;
    
            System.out.println(s1);
            System.out.println(s2);
            System.out.println(s3);
    
        }
    }
    
    //执行结果
    hello
    world
    hello
    

    在这里插入图片描述

    在这里插入图片描述

  • 在Java中""引起来的也是String类型对象:

    //打印"hello"字符串的长度
    System.out.println("hello".length());
    

2.2 字符串比较

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

    • 对于内置类型,==比较的是变量中的值;

    • 对于引用类型,==比较的是引用中的地址;

代码示例:

  package demo2;
   
   public class Test1 {
       public static void main(String[] args) {
           int a = 10;
           int b = 20;
           int c = 10;
   
           //对于基本类型变量,==比较两个变量中存储的值是否相同
           System.out.println(a == b);
           System.out.println(a == c);
   
           System.out.println("======================");
           
           //对于引用类型变量,==比较两个引用变量引用的是否为同一个对象
           String s1 = new String("hello");
           String s2 = new String("hello");
           String s3 = new String("world");
           String s4 = s1;
   
           System.out.println(s1 == s2);
           System.out.println(s2 == s3);
           System.out.println(s1 == s4);
   
       }
   
   }
   
   //执行结果
   false
   true
   ======================
   false
   false
   true

2.equals(String str)

equals的返回的是boolean类型,String类重写了Object类(原按==比较)中的equals方法,可直接进行比较

package demo2;

public class Test3 {
    public static void main(String[] args) {
        String s1 = "aa";
        String s2 = "ab";
        String s3 = "aa";
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));
    }
}

//执行结果
false
true
  1. copareTo(String str)

    compareTo返回的是int类型,具体比较方式:

    • 先按照字典次序(字符大小的顺序)进行比较,如果出现不等的字符,直接返回这两个字符的大小差值

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

package demo2;

public class Test2 {
    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.compareTo(s2));
        System.out.println(s1.compareTo(s3));
        System.out.println(s1.compareTo(s4));
       
    }
}
//执行结果
-1
0
-3
  1. compareTolgnoreCase(String str)
    比较方法与compareTo相同,但忽略大小写比较
package demo2;
   
   public class Test2 {
       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));
           System.out.println(s1.compareToIgnoreCase(s3));
           System.out.println(s1.compareToIgnoreCase(s4));
       }
   }
//执行结果
-1
0
-3   

2.3 字符串查找

字符串查找是字符串中非常常见的操作,String类提供的常用查找方法有:

方法功能
char charAt(int index)返回index位置上字符,如果index为负数或者越界,抛出 IndexOutOfBoundsException异常
int indexOf(int ch)返回ch第一次出现的位置,没有返回-1
int indexOf(int ch, int fromIndex)从fromIndex位置开始找ch第一次出现的位置,没有返回-1
int indexOf(String str)返回str第一次出现的位置,没有返回-1
int indexOf(String str, int fromIndex)从fromIndex位置开始找str第一次出现的位置,没有返回-1
int lastIndexOf(int ch)从后往前找,返回ch第一次出现的位置,没有返回-1
int lastIndexOf(int ch, int fromIndex)从fromIndex位置开始找,从后往前找ch第一次出现的位置,没有返 回-1
int lastIndexOf(String str)从后往前找,返回str第一次出现的位置,没有返回-1
int lastIndexOf(String str, int fromIndex)从fromIndex位置开始找,从后往前找str第一次出现的位置,没有返 回-1
package demo3;

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

        String s = "aaabbbcccaaabbbccc";
        System.out.println(s.charAt(3)); // b
        System.out.println(s.indexOf('c')); // 6
        System.out.println(s.indexOf('c',10)); // 15
        System.out.println(s.indexOf("bbb")); // 3
        System.out.println(s.indexOf("bbb",10)); // 12
        System.out.println(s.lastIndexOf('c')); // 17
        System.out.println(s.lastIndexOf('c',10)); // 8
        System.out.println(s.lastIndexOf("bbb")); // 12
        System.out.println(s.lastIndexOf("bbb",10)); // 3

    }
}

在这里插入图片描述

2.4 转化

  1. 数值和字符串转化

    package demo4;
    class Cat {
        protected String name;
        protected int age;
    
        public Cat(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
    public class Test1 {
        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 Cat("虾米",5));
            System.out.println(s1);
            System.out.println(s2);
            System.out.println(s3);
            System.out.println(s4);
    
            System.out.println("===================");
    
            //字符串转数字
            int data1 = Integer.parseInt(s1);
            double data2 = Double.parseDouble(s2);
            System.out.println(data1);
            System.out.println(data2);
        }
    }
    

    在这里插入图片描述

  2. 大小写转换

    package demo4;
    
    public class Test2 {
        public static void main(String[] args) {
            String s1 = "hello";
            String s2 = "WORLD";
                
            //小写转大写 toUpperCase()
            System.out.println(s1.toUpperCase());
            //大写转小写 toLowerCase()
            System.out.println(s2.toLowerCase());
        }
    }
    
    //执行结果
    HELLO
    world
    

    在这里插入图片描述

  3. 字符串转数组

    package demo4;
    
    public class Test3 {
        public static void main(String[] args) {
            String s = "hello";
            //字符串转数组
            char[] ch = s.toCharArray();
            for (int i = 0; i < ch.length; i++) {
                System.out.println(ch[i]);
            }
            System.out.println("=========");
            //数组转字符串
            String s2 = new String(ch);
            System.out.println(s2);
        }
    }
    
    //执行结果
    h
    e
    l
    l
    o
    =========
    hello
    

    在这里插入图片描述

  4. 格式化

    package demo4;
    
    public class Test4 {
        public static void main(String[] args) {
    
            String s1 = String.format("%d-%d-%d",2023,7,25);
            System.out.println(s1);
    
        }
    }
    
    //执行结果
    2023-7-25
    

    在这里插入图片描述

2.5 字符串替换

使用一个指定的新的字符串替换掉已有的字符串数据

方法功能
String replaceAll(String regex, String replacement)替换所有的指定内容
String replaceFirst(String regex, String replacement)替换首个内容

代码示例:

package demo5;

public class Test1 {
    public static void main(String[] args) {
        String s = "hello world";
        s.replaceAll("l","&"); //注:这里只是创建了一个新的字符串并进行字符串的替换,并不是对s本身进行修改
        System.out.println(s);
        System.out.println(s.replaceAll("l","&"));

        System.out.println(s.replaceFirst("l","&"));

    }
}

//执行结果
hello world
he&&o wor&d
he&lo world

在这里插入图片描述

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

2.6 字符串拆分

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

方法功能
String[] split(String regex)将字符串全部拆分
String[] split(String regex, int limit)将字符串以指定的格式,拆分为limit组

代码示例:

package demo6;

public class Test1 {
    public static void main(String[] args) {
        String s1 = "hello world ha ha";
        String[] result1 = s1.split(" "); //根据空格拆分
        for (String x:result1) {
            System.out.println(x);
        }

        System.out.println("============");
        String[] result2 = s1.split(" ",2); //
        for (String x:result2) {
            System.out.println(x);
        }
    }
}


//执行结果
hello
world
ha
ha
============
hello
world ha ha  

在这里插入图片描述

有一些特殊字符作为分隔符可能无法正确切分,需要加上转义:

package demo6;

public class Test2 {
    public static void main(String[] args) {
        String s = "192.168.1.1";
        String[] result = s.split("\\.");
        for (String x:result) {
            System.out.println(x);
        }

    }
}

//执行结果
192
168
1
1

注:

  1. 字符"|“,”*“,”+"都得加上转义字符,前面加上"\\";
  2. 如果需要"\",则要写成"\\\\";
  3. 一个字符串中有多个分隔符,可以用"|"作为连字符

多次拆分代码示例:

package demo6;

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

        String s = "name=XiaoMa&age=19";
        String[] result = s.split("&");
        for (int i = 0; i < result.length; i++) {
            String[] temp = result[i].split("=");
            System.out.println(temp[0] + " = " + temp[1]);
        }
        
    }
}

//执行结果
name = XiaoMa
age = 19

在这里插入图片描述

2.7 字符串截取

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

方法功能
String substring(int beginIndex)从指定索引截取到结尾
String substring(int beginIndex, int endIndex)截取部分内容

代码示例:

package demo7;

public class Test1 {
    public static void main(String[] args) {
        String s = "hello world";
        System.out.println(s.substring(3));
        System.out.println(s.substring(3,7));
    }
}

//执行结果
lo world
lo w

在这里插入图片描述

注:

  1. 索引从0开始
  2. 主要前闭开区间的写法,substring(3,7)表示包含3下标的字符,不包含7下标的字符

2.8 字符串去空格

String trim() : 去掉字符串中的左右空格,保留中间空格

package demo8;

public class Test1 {
    public static void main(String[] args) {
        String s = " hello world ";
        System.out.println("[" + s + "]");
        System.out.println("[" + s.trim() + "]");
    }
}

//执行结果
[ hello world ]
[hello world]

在这里插入图片描述

注:trim()会去掉字符串开头和结尾的空白字符(空格,换行,制表符等)

3.字符串的不可变性

Strin是一种不可变对象,字符串中的内容是不可改变的,字符串本身不能被修改,原因如下:

  1. String类在设计时就是不可改变的:

    在这里插入图片描述

    在这里插入图片描述

    String类中的字符实际保存在内部维护的value字符数组中,由图还可以看出:

    • String类被final修饰,表明该类不能被继承

    • value被final修饰,表明value不能引用其他字符数组,但是奇引用空间中的内容可以修改

      package demo9;
      
      import java.util.Arrays;
      
      public class Test1 {
          public static void main(String[] args) {
              final int[] arr = {1,2,3};
              arr[0] = 100;
              System.out.println(Arrays.toString(arr));
              //arr = new int[] {4,5,6}; //编译报错:java: 无法为最终变量arr分配值
          }
      }
      
      //执行结果
      [100, 2, 3]
      
  2. 所有涉及到可能修改字符串内容的操作都是创建一个新对象,改变的是新对象

    比如replace方法:

    在这里插入图片描述

代码示例:

package demo10;

public class Test1 {
    public static void main(String[] args) {
        String s = "Hello World";
        s.replace('l','&');
        System.out.println(s);
        System.out.println(s.replace('l','&'));
    }
}

//执行结果
Hello World
He&&o Wor&d

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值