String 类的常用字符串方法

public class Page106 {

    /**
     * 字符串练习第五章
     * @param args
     */
    public static void main(String[] args) {
        String str=new String(" WOrld ");
        String str1=new String("w,o,r;l;d");
        System.out.println(str.length());//获取长度
        System.out.println(str.toUpperCase());//转为大写
        System.out.println(str.toLowerCase());//转为小写
        System.out.println(str.trim());//去掉首尾的空格
        System.out.println(str.trim().length());
        System.out.println(str.equals(str1));//比较是否相等,区分大小写
        System.out.println((str.trim()).equalsIgnoreCase(str1));//不区分大小写
        //查找
        System.out.println(str.indexOf("or"));//返回第一次出现这个字符的位置,如果没有找到返回-1
        System.out.println(str.lastIndexOf('l'));//返回最后一次出现这个字符的位置
        System.out.println(str.lastIndexOf("lp",4));//从字符串第四个索引位置开始找lp最后一次出现的位置
        System.out.println(str1.charAt(3));//返回索引位置为3的字符
        //截取
        System.out.println(str.substring(2, 4));//截取索引位置为2-4之间的字符
        //分割
        String[] array1=str1.split(",");
        String[] array2=str1.split(";",3);//分割;标志的字符串,指定分割字符数为3,返回的字符存放在字符串数组中
        for(int i=0;i<array1.length;i++){
            System.out.print(array1[i]+"\t");
        }
        System.out.println();
        for(int i=0;i<array2.length;i++){
            System.out.print(array2[i]+"\t");
        }
        //替换
        String s="hello world,hello world";
        System.out.println(s.replace("world", "java"));//用java替换所有的world
        System.out.println(s.replaceFirst("world", "java"));//用java只替换第一次出现的world
        System.out.println(s.replaceAll("world", "java"));//用将咪表字符串匹配的正则表达式的所有子字符串替换成新的
        //链接
        System.out.println(s.concat(str1));//在s字符串后链接str1字符串
}
}

结果显示:

7
 WORLD 
 world 
WOrld
5
false
false
-1
4
-1
,
Or
w    o    r;l;d    
w,o,r    l    d    hello java,hello java
hello java,hello world
hello java,hello java
hello world,hello worldw,o,r;l;d

 

posted @ 2016-10-24 16:37  那一年的我们  阅读(364)  评论(0编辑  收藏  举报