美文网首页
String的常见方法

String的常见方法

作者: suming182002 | 来源:发表于2017-09-16 10:10 被阅读0次

String字符串方法练习

public class StringDemo {
    private String demoString = "ceshiSumingming";
    public void testString(){
        //字符串拼接
        String dsg = demoString.concat("dameinv");
        System.out.println(dsg);
      
        //输出字符串长度
        int len = demoString.length();
        System.out.println(len);
        
        //判断字符串是否相等
        boolean eq = demoString.equals("Sumingming");
        System.out.println(eq);
        
        //取字符串的某几位,(5,9)代表第6到第9位
        String sub = demoString.substring(5,9);
        System.out.println(sub);
        
        //取字符串第字符串的第n+1位到末尾
        String sub1 = demoString.substring(5);
        System.out.println(sub1);
      
        //判断字符串是否以某字符串开头
        boolean sw = demoString.startsWith("ceshi");
        System.out.println(sw);
        
        //判断字符串是否以某字符串结尾
        boolean jw = demoString.endsWith("ming");
        System.out.println(jw);
      
        //找出子字符串在字符串中第一次出现的index,若找不到则返回-1
        int subindex = demoString.indexOf("Suming");
        System.out.println(subindex);
      
        //找出子字符串在字符串中最后一次出现的index,若找不到则返回-1
        int lastindex = demoString.lastIndexOf("g");
        System.out.println(lastindex);
        
        //将字符串中所有的小写字母变成大写
        System.out.println(demoString.toUpperCase());
        //将字符串中所有的小写字母变成小写
        System.out.println(demoString.toLowerCase());
        
        //将字符串中开头的空格去掉
        System.out.println("  woshixiaoming".trim());
        
        //将字符串中的某段子字符串替换新子字符串
        String subreplace = demoString.replace("ceshi","meinv");
        System.out.println(subreplace);
        
        //将字符串中第一次的某子字符串替换成新子字符串,支持正则
        String subreplaceF = demoString.replaceFirst("s","S");
        System.out.println(subreplaceF);
        
        //将字符串中所有的某子字符串替换成新子字符串,支持正则,与replace的区别是否支持正则
        String subreplaceA = demoString.replaceAll("m","M");
        System.out.println(subreplaceA);

    }

    public static void main(String[] args){
        StringDemo t = new StringDemo();
        t.testString();
    }
}

相关文章

网友评论

      本文标题:String的常见方法

      本文链接:https://www.haomeiwen.com/subject/jrjysxtx.html