2021-10-06

话不多说,直接上干货,后续会出更多小知识!

第一章:String类中常用的成员方法

1.String的常见方法

concat: 拼接字符串,功能和字符串的+操作类似
contains: 判断是否包含
startsWith: 判断是否以什么开头的     
endsWith: 判断是否以什么结尾的      
indexOf:  查找第一次出现的索引
lastIndexOf: 查找最后一次出现的索引
replace: 替换
substring: 截取
toCharArray: 转成字符数组
split: 分割/切割字符串
trim: 去两端空格
toLowerCase: 转成小写
toUpperCase: 转成大写

2.常见方法演示

public class TestString {
    public static void main(String[] args) {
        //concat: 拼接字符串,功能和字符串的+操作类似
        String s1 = "Hello";
        s1 = s1.concat("World");
        System.out.println(s1);
        //思考: concat 和  + 有什么区别
        //a.concat只能用于2个字符串拼接, 而+可以拼接字符串和任意的其他类型
        //b.性能上来看:concat性能略高于+

        //contains: 判断是否包含
        String s2 = "HelloJavaWorld";
        System.out.println(s2.contains("Java"));

        //startsWith: 判断是否以什么开头的
        String s3 = "HelloJavaWorld";
        System.out.println(s3.startsWith("Hel")); //判断姓
        //endsWith: 判断是否以什么结尾的
        String s4 = "HelloJavaWorld";
        System.out.println(s4.endsWith("rld")); // 判断文件的格式

        //indexOf:  查找第一次出现的索引
        String s5 = "HelloJavaHelloWorld";
        System.out.println(s5.indexOf("Hello"));
        //lastIndexOf: 查找最后一次出现的索引
        String s6 = "HelloJavaHelloWorld";
        System.out.println(s6.lastIndexOf("Hello"));

        //replace: 替换
        String s7 = "Hello程序员Hello程序员";
        s7 = s7.replace("程序员","***");
        System.out.println(s7);

        //substring: 截取
        String s8 = "HelloJavaWorld";
        //s8 = s8.substring(5, 9); //含头不含尾
        //System.out.println(s8);
        s8 = s8.substring(5); //从指定索引开始截取直到字符串结束
        System.out.println(s8);

        //toCharArray: 转成字符数组
        String s9 = "Hello";
        char[] chs = s9.toCharArray();
        System.out.println(Arrays.toString(chs));

        //split: 分割/切割字符串
        String s10 = "0550-3004-3334-6468";
        String[] nums = s10.split("-");
        System.out.println(Arrays.toString(nums));

        //trim: 去两端两端两端空格
        String s11 = "   Hello  World  ";
        System.out.println("--->"+s11+"<---");
        s11 = s11.trim();
        System.out.println("--->"+s11+"<---");

        //toLowerCase: 转成小写
        String s12 = "HelloWorld";
        s12 = s12.toLowerCase();
        System.out.println(s12);
        //toUpperCase: 转成大写
        String s13 = "HelloWorld";
        s13 = s13.toUpperCase();
        System.out.println(s13);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值