String类常用方法(Java)

在c语言中已经涉及到字符串了,但在c语言中要表示字符串只能使用字符数组或字符指针可以使用标准库中的字符串系列函数完成大部分操作,但是这种将数据和操作数据方法分开的方式不符合面向对象的思想。而字符串应又非常广泛。因此Java专门提供了String类。

1.字符串构造

常用的有以下三种:

public static void main(String[] args) {
        //1、使用常量串构造
        String s1 = "hello world";

        //2、直接new String对象
        String s2 = new String("hello world");

        //3、使用字符数组进行构造
        char[] array = {'h','e','l','l','o'};
        String s3 = new String(array);
    }

注意:String是引用类型,内部并不储存字符串本身。

String s1 = new String("hello");
        String s2 = new String("world");
        String s3 = s1;

        System.out.println(s1.length());//获取字符串长度--5
        System.out.println(s1.isEmpty());//如果字符串长度为零,则返回true,否则返回false

在Java中用""引起来的也是String类型对象。

        System.out.println("hello".length());

2.  String对象的比较

字符串的比较是常见的操作之一,比如字符串排序,java当中提供了四种方式:

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

注意:对于内置类型,== 比较的是变量当中的值,对于引用类型 == 比较的是引用中的地址。

public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = 10;

        //对于基本数据类型 == 比较的是两个变量当中存储的值是否相同
        System.out.println(a == b);//false
        System.out.println(a == c);//true

        //对于引用类型变量 == 比较的是两个引用变量引用的是否为同一个对象
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = new String("world");
        String s4 = s1;
        System.out.println(s1 == s2);//false
        System.out.println(s1 == s3);//false
        System.out.println(s1 == s4);//true
    }

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

字典序:字符大小的顺序。

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

 public boolean equals(Object anObject) {
// 1. 先检测this 和 anObject 是否为同一个对象比较,如果是返回true
        if (this == anObject) {
            return true;
        }
// 2. 检测anObject是否为String类型的对象,如果是继续比较,否则返回false
        if (anObject instanceof String) {
// 将anObject向下转型为String类型对象
            String anotherString = (String) anObject;
            int n = value.length;//这里的value指的是s1;
// 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;
    }
 System.out.println(s1.equals(s2));//true

3.int compareTo(String str)

与equals不同的是,equals返回的是Boolean类型,而compareTo返回的是int类型

1. 先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值。
2. 如果前 k 个字符相等 (k 为两个字符长度最小值 ) ,返回值两个字符串长度差值。 
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));//-1:不同输出字符差值
        System.out.println(s1.compareTo(s3));//0:相同输出
        System.out.println(s1.compareTo(s4));//-3:前K个字符相同,输出长度差值
    }

4.int compareToIgnoreCase(String str)方法:与compareTo相同只是忽略大小写

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));//-3:前K个字符相同,输出长度差值
    }

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

下面进行代码演示:

 public static void main(String[] args) {
        String s = new String("aaabbbcccaaabbbccc");
        System.out.println(s.charAt(1));//a
        System.out.println(s.indexOf('c'));//6
        System.out.println(s.indexOf('c',10));//15
        System.out.println(s.indexOf("ccc"));//6
        System.out.println(s.indexOf("ccc",10));//15
        System.out.println(s.lastIndexOf('b'));//14
        System.out.println(s.lastIndexOf('b',10));//5
        System.out.println(s.lastIndexOf("bbb"));//12
        System.out.println(s.lastIndexOf("bbb",10));//3
    }

4.转化

1.数值和字符串转化

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("Han",18));
        System.out.println(s1);//1234
        System.out.println(s2);//12.34
        System.out.println(s3);//true
        System.out.println(s4);//Student@1b6d3586
        int data1 = Integer.parseInt("1234");
        double data2 = Double.parseDouble("12.34");
        System.out.println(data1);//1234
        System.out.println(data2);//12.34

    }

2.大小写转化

public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO";
        //小写转大写
        System.out.println(s1.toUpperCase());//HELLO
        //大写转小写
        System.out.println(s2.toLowerCase());//hello
    }

3.字符串转数组

 public static void main(String[] args) {
        String s = "hello";
        //字符串转数组
        char[] ch = s.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            System.out.print(ch[i]);//hello
        }
        System.out.println();
        //数组转字符串
        String s2 = new String(ch);
        System.out.println(s2);//hello
    }

4.格式化

 public static void main(String[] args) {
        String s = String.format("%d-%d-%d",2023,12,15);
        System.out.println(s);//2023-12-15
    }

5.字符串替换

使用一个指定的新的字符串替换掉已有的字符串数据,可用的方法如下:
方法功能
String replaceAll(String regex, String replacement)
替换所有的指定内容
String replaceFirst(String regex, String replacement)
替换首个内容
 public static void main(String[] args) {
        String s ="helloworld";
        System.out.println(s.replaceAll("l","-"));//he--owor-d
        System.out.println(s.replaceFirst("l","-"));//he-loworld
    }
注意事项: 由于字符串是不可变对象, 替换不修改当前字符串, 而是产生一个新的字符串。

6.字符串拆分

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

方法功能
String[] split(String regex)
将字符串全部拆分
String[] split(String regex, int limit)
将字符串以指定的格式,拆分为 limit
 public static void main(String[] args) {
        String s = "hello hello hello world";
        //实现字符串的拆分
        String[] str = s.split(" ");//以空格为标准拆分
        for (String s1:str
             ) {
            System.out.println(s1);
        }
        System.out.println();
        //实现字符串的部分拆分
        String[] str1 = s.split(" ",2);//以第一个空格为标准拆分成两部分
        for (String s2:str1
             ) {
            System.out.println(s2);
        }
    }
注意:拆分是特别常用的操作. 一定要重点掌握. 另外有些特殊字符作为分割符可能无法正确切分, 需要加上转义.

7.字符串截取

从一个完整的字符串之中截取出部分内容。可用方法如下:
功能作用
String substring(int beginIndex)
从指定索引截取到结尾
String substring(int beginIndex, int endIndex)
截取部分内容
public static void main(String[] args) {
        String s = "helloworld";
        System.out.println(s.substring(5));//world
        System.out.println(s.substring(0,5));//hello
    }

注意:

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

8.其他操作

//trim 会去掉字符串开头和结尾的空白字符(空格, 换行, 制表符等)
        String str = " hello world";
        System.out.println("["+str+"]");//[ hello world]
        System.out.println("["+str.trim()+"]");//[hello world]

9.字符串的不可变性

String 是一种不可变对象 . 字符串中的内容是不可改变。字符串不可被修改,是因为:
1. String 类在设计时就是不可改变的, String类实现描述中已经说明了。
  String 类中的字符实际保存在内部维护的 value 字符数组中
1. String 类被 final 修饰,表明该类不能被继承
2. value 被修饰被 final 修饰,表明 value 自身的值不能改变,即不能引用其它字符数组,但是其引用空间中的内容可以修改。
2. 所有涉及到可能修改字符串内容的操作都是创建一个新对象,改变的是新对象。
final 修饰类表明该类不想被继承, final 修饰引用类型表明该引用变量不能引用其他对象,但是其引用对象中的内 容是可以修改的

10.字符串修改

注意:尽量避免直接对 String 类型对象进行修改,因为 String 类是不能修改的,所有的修改都会创建新对象,效率 非常低下。
public static void main(String[] args) {
        String str = "hello";
        str += "wolrd";
        System.out.println(str);//hellowolrd
    }
但是这种方式不推荐使用,因为其效率非常低,中间创建了好多临时对象。
  • 22
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值