Java_String的操作

本文详细介绍了Java中String类的常用方法,包括charAt用于获取指定位置的字符,length用于获取字符串长度,split用于按指定分隔符分割字符串,substring用于截取子字符串,replace用于替换字符,以及compareTo用于字符串之间的比较。

1.public char charAt(int index)
返回字符串中第index个字符;

String  s1 = "Hello World"

System.out.println(s1.charAt(4)) // 输出o

2.public int length()
返回字符串的长度;

System.out.println(s1.length) // 输出11

3.public String[] split(String regex)
将一个字符串按照指定的分隔符分隔,返回分隔后的字符串数组

 String date = "2008/09/10";
            String[ ] dateAfterSplit= new String[3];
            dateAfterSplit=date.split("/");         //以“/作为分隔符来分割date字符串,并把结果放入3个字符串中。

            for(int i=0;i<dateAfterSplit.length;i++)
                       System.out.print(dateAfterSplit[i]+" ");
      }

输出结果:2008 09 10

4.public String substring(int beginIndex,int endIndex)
返回该字符串从beginIndex开始到endsIndex结尾的子字符串

System.out.println(s1.substring(1,3)) // 输出ell字符串

5.public String replace(char oldchar,char newChar)
在字符串中用newChar字符替换oldChar字符

System.out.println(s1.replace("o" ,"123")) // 输出Hell123 World字符串

6.int compareTo(String anotherString) 

当前String对象与anotherString比较

String s2 = "HelloWorld"

String s3 = "Hello World"

String s4 = "HelloWorldabc"

System.out.println(s1.compareTo(s2)) // 输出5

System.out.println(s1.compareTo(s3)) // 输出0

 

 

转载于:https://www.cnblogs.com/lcl15/p/6899910.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值