String类的其他功能replace、compareTo

本文详细介绍了 Java 中 String 类的一些实用方法,包括字符串替换、去除两端空格、比较字符串等基本操作,并通过示例代码展示了这些方法的具体使用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package cn.lgt.stringmethods;

public class StringOtherMethods {
    public static void stringOtherMehtods(){
        //String类的其他功能

        //替换功能
        //1. String replace(char old, char new);
        //2. String replace(String old, String new);
        String s1 = "helloworld";
        System.out.println(s1.replace('o', 'm'));
        System.out.println(s1.replace("world", "java"));
        //去除字符串两端的空格
        //String trim();
        String s2 = " dd sss  d   ";
        System.out.println(s2.trim());
        //按照字典顺序比较两个字符串
        //int compareTo(String str);//区分大小写
        //int compareToIgnoreCase(String str);//不区分大小写
        String s3 = "helloworld";
        String s4 = "HELLOWORLD";
        String s5 = "hello";
        String s6 = "world";
        System.out.println(s3.compareTo(s5));//前面都相同,返回相差的字符数
        System.out.println(s3.compareToIgnoreCase(s4));//不区分大小写,相同,返回数值0
        System.out.println(s3.compareTo(s6));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值