《String类的常用方法》

String类的常用方法应用实例

1. equals:比较字符串内容,区分大小写

2. equalsIgnoreCase :忽略大小写,判断内容是否相等

public class StringMethod {
    public static void main(String[] args) {
        String name1 = "hello";
        String name2 = "Hello";
        // equals
        System.out.println(name1.equals(name2)); // false
        // equalsIgnoreCase
        System.out.println(name1.equalsIgnoreCase(name2)); // true
    }
}

3.length : 获取字符串的长度,字符的个数。

4.indexOf : 获取字符在字符串对象中第一次出现的索引,索引从 0 开始,如果找不到, 返回-1。

5.lastIndexOf : 获取字符在字符串对象中最后一次出现的索引,索引从 0 开始,如果找不到, 返回-1。

public class StringMethod {
    public static void main(String[] args) {
       
        String str = "abc@abc@";
        int index1 = str.indexOf('@');
        int index2 = str.indexOf('d');
        int index3 = str.lastIndexOf('@');
        System.out.println(str.length()); //8
        System.out.println(index1); //3
        System.out.println(index2); //-1
        System.out.println(index3); //7
        System.out.println(str.indexOf("abc")); //0
    }
}

6.substring : 截取指定范围的字符串.(截取到索引减一)

public class StringMethod {
    public static void main(String[] args) {
     
        String str1 = "hello,张三";
        System.out.println(str1.substring(6)); //截取后面的字符 -> 张三
        System.out.println(str1.substring(0,5));// 索引从 0 - 5 截取 -> hello
        System.out.println(str1.substring(2,5));// -> oll
    }
}

7.toUpperCase : 转大写

8.toLowerCase : 转小写

9.concat :连接字符串

10.replace : 替换字符串的字符

11.split : 分割字符串,对于某些分割字符,我们需要转义 比如 | \\ 等

12.compareTo : 比较两个字符串的大小

13.toCharArray : 转换为字符数组

14.format : 格式化字符串,%s 字符串,%c 字符,%d 整型,%.2f 浮点型四舍五入) 

15.charAt : 获取索引处的字符

String s = "jack";
System.out.println(s.charAt(2)); // c

注意: 不能使用 s[2]来获取字符 ,s 是一个对象,不是数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值