Java中String类的方法及说明(二)

Java中String类的常用方法:

public char charAt(int index)

返回字符串中第index个字符;
public int length()
返回字符串的长度;
public int indexOf(String str)
返回字符串中第一次出现str的位置;
public int indexOf(String str,int fromIndex)
返回字符串从fromIndex开始第一次出现str的位置;
public boolean equalsIgnoreCase(String another)
比较字符串与another是否一样(忽略大小写);
public String replace(char oldchar,char newChar)
在字符串中用newChar字符替换oldChar字符
public boolean startsWith(String prefix)
判断字符串是否以prefix字符串开头;
public boolean endsWith(String suffix)
判断一个字符串是否以suffix字符串结尾;
public String toUpperCase()
返回一个字符串为该字符串的大写形式;
public String toLowerCase()
返回一个字符串为该字符串的小写形式
public String substring(int beginIndex)
返回该字符串从beginIndex开始到结尾的子字符串;
public String substring(int beginIndex,int endIndex)
返回该字符串从beginIndex开始到endsIndex结尾的子字符串
public String trim()
返回该字符串去掉开头和结尾空格后的字符串
public String[] split(String regex)
将一个字符串按照指定的分隔符分隔,返回分隔后的字符串数组
实例:  
public class SplitDemo{
     public static void main (String[] args) {

             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          //结果为分割后的3个字符串

实例:
TestString1.java:
程序代码
public class TestString1
{
    public static void main(String args[]) {
        String s1 = "Hello World" ;
        String s2 = "hello world" ;
        System.out.println(s1.charAt(1)) ;
        System.out.println(s2.length()) ;
        System.out.println(s1.indexOf("World")) ;
        System.out.println(s2.indexOf("World")) ;
        System.out.println(s1.equals(s2)) ;
        System.out.println(s1.equalsIgnoreCase(s2)) ;

        String s = "我是J2EE程序员" ;
        String sr = s.replace('我','你') ;
        System.out.println(sr) ;
    }
}

TestString2.java:
程序代码

public class TestString2
{
    public static void main(String args[]) {
        String s = "Welcome to Java World!" ;
        String s2 = "   magci   " ;
        System.out.println(s.startsWith("Welcome")) ;
        System.out.println(s.endsWith("World")) ;
        String sL = s.toLowerCase() ;
        String sU = s.toUpperCase() ;
        System.out.println(sL) ;
        System.out.println(sU) ;
        String subS = s.substring(11) ;
        System.out.println(subS) ;
        String s1NoSp = s2.trim() ;
        System.out.println(s1NoSp) ;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值