String类常用方法

本文详细介绍了Java String类中的核心方法,如charAt(), compareTo(), endsWith(), equals()等,展示了字符串操作的实例,并覆盖了字符比较、连接、查找和结束判断等功能。

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

说明:①、所有方法均为public。

             ②、书写格式: [修饰符] <返回类型><方法名([参数列表])>

      例如:static int parseInt(String s)

      表示此方法(parseInt)为类方法(static),返回类型为(int),方法所需要为String类型。

1. char charAt(int index) :取字符串中的某一个字符,其中的参数index指的是字符串中序数。字符串的序数从0开始到length()-1 。

    例如:String s = new String(“abcdefghijklmnopqrstuvwxyz”);

          System.out.println(“s.charAt(5): ” + s.charAt(5) );

          结果为: s.charAt(5): f

2. int compareTo(String anotherString) :当前String对象与anotherString比较。相等关系返回0;不相等时,从两个字符串第0个字符开始比较,返回第一个不相等的字符差,另一种情况,较长字符串的前面部分恰巧是较短的字符串,返回它们的长度差。

3. int compareTo(Object o) :如果o是String对象,和2的功能一样;否则抛出ClassCastException异常。

    例如:String s1 = new String(“abcdefghijklmn”);

            String s2 = new String(“abcdefghij”);

           String s3 = new String(“abcdefghijalmn”);

           System.out.println(“s1.compareTo(s2): ” + s1.compareTo(s2) ); //返回长度差

           System.out.println(“s1.compareTo(s3): ” + s1.compareTo(s3) ); //返回‘k’-'a’的差

           结果为:s1.compareTo(s2): 4

                       s1.compareTo(s3): 10

4. String concat(String str) :将该String对象与str连接在一起。

5. boolean contentEquals(StringBuffer sb) :将该String对象与StringBuffer对象sb进行比较。

6. static String copyValueOf(char[] data) :

7. static String copyValueOf(char[] data, int offset, int count) :这两个方法将char数组转换成String,与其中一个构造函数类似。

8. boolean endsWith(String suffix) :该String对象是否以suffix结尾。

    例如:String s1 = new String(“abcdefghij”);

           String s2 = new String(“ghij”);

           System.out.println(“s1.endsWith(s2): ” + s1.endsWith(s2) );

           结果为:s1.endsWith(s2): true

9. boolean equals(Object anObject) :当anObject不为空并且与当前String对象一样,返回true;否则,返回false。

10. byte[] getBytes() :将该String对象转换成byte数组。

11. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) :该方法将字符串拷贝到字符数组中。其中,srcBegin为拷贝的起始位置、srcEnd为拷贝的结束位置、字符串数值dst为目标字符数组、dstBegin为目标字符数组的拷贝起始位置。

     例如:char[] s1 = {‘I’,' ’,'l’,'o’,'v’,'e’,' ’,'h’,'e’,'r’,'!’};//s1=I love her!

           String s2 = new String(“you!”); s2.getChars(0,3,s1,7); //s1=I love you!

           System.out.println( s1 );

           结果为:I love you!

12. int hashCode() :返回当前字符的哈希表码。

13. int indexOf(int ch) :只找第一个匹配字符位置。

14. int indexOf(int ch, int fromIndex) :从fromIndex开始找第一个匹配字符位置。

15. int indexOf(String str) :只找第一个匹配字符串位置。

16. int indexOf(String str, int fromIndex) :从fromIndex开始找第一个匹配字符串位置。

更多请见:http://www.mark-to-win.com/tutorial/50316.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值