Java String类的方法总结,附加使用。

本文详细介绍了Java中字符串的使用方法,包括String、StringBuffer和StringBuilder的区别,以及如何使用String类的各种方法进行字符串处理,例如拼接、比较、查找子串等。

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

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

        //String 是不可变的
        //StringBuffer 和 StringBuilder是可变的

        String s   = new String("hello w");

        String s1 = new String("hello wolll");

        StringBuffer sb = new StringBuffer("hello w");

        char[] c = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
        //获取字符串的指定位置的字符
        //System.out.println("s.charAt(4) : " + s.charAt(4));

        /*比较两个字符串的大小,如果两个字符串的字符序列相等,则返回0
        不相等时,从两个字符串第-个字符开始比较,返回第一个不相等的字符差*/
        //System.out.println("s.compareTo(s1)); ==> 4

        //进行字符串的连接与字符串 + 的功能相同
        //System.out.println("s.concat(s1) : "+ s.concat(s1));

        /*将String对象与StringBuffer对象sb进行比较,
        当它们包含的字符序列相同时返回true。*/
        //System.out.println("s.contentEquals(sb) : " + s.contentEquals(sb));

        //将字符数组连缀成字符串从1开始,长度为6  "ello w"
        //String.copyValueOf(c)整个字符数组连缀成字符串
        //System.out.println(String.copyValueOf(c, 1, 6));

        //将该字符串与指定对象比较,如果两者包含的字符序列相等,则返回true,否则返回false
        //System.out.println(s.equals(s1));

        //与前一个方法相似,只是忽略大小写
        //System.out.println(s.equalsIgnoreCase(s1));

        //endsWith(String suffix)返回该String对象是否以suffix结尾
        //System.out.println(s1.endsWith("olll"));

        //startsWith(String suffix)返回该String对象是否以suffix开头
        //System.out.println(s1.startsWith("he"));

        //将该String对象转换成byte数组
        //byte[]  bt = s.getBytes();

        /* void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
        该方法将字符串中从srcBegin开始,到srcEnd结束的字符复制到dst字符数组
        中,其中dstBegin为目标字符数组的起始复制位置。*/
        //s1.getChars(3, 6, c, 5);
        //System.out.println(c);

        //int indexOf(String str)找出str子字符在该字符串中第一次出现的位置。
        //System.out.println(s.indexOf("ell"));

        //int lastIndexOf(String str)找出str子字符在该字符串中第最后一次出现的位置。
        //System.out.println(s1.lastIndexOf("o"));

        //返回当前字符串的长度
        //System.out.println(s1.length());

        /*String substring(int beginIndex); 获取从beginIndex开始的子串
        String substring(int beginIndex, int endIndex);获取beginIndex位置开始到
        endIndex的子字符串。*/
        //System.out.println(s1.substring(3));
        //System.out.println(s1.substring(3, 6));

        //char[] toCharArray() 将String对象转换为char数组
        //String toLowerCase() 将字符串转换成小写
        //String toUpperCase() 讲字符串转换成大写

        //static String valueOf(X x) 将基本类型值转换为String对象的方法
        //System.out.println(String.valueOf(18));



    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值