String类常用功能

String类常用功能

判断:

        boolean equals(Object obj)   
        boolean equalsIgnoreCase(String str)  //忽略大小写
        boolean startsWith(String str)  //是否以..开始
        boolean endsWith(String str)
        eg:
            String s1="hello";
            String s2="hello";
            s1.equals(s2); //true

获取:

        int length()  
        char charAt(int index)  //索引获取字符
        int indexOf(String str)  //str第一次出现的索引
        String substring(int start)  // 从..开始截取字符串至结束
        String substring(int start, int end)

转换:

        char[] toCharArray()  
        String toLowerCase()
        String toUpperCase()
        eg:
            String s="abcde";
            char[] chs = s.toCharArray();  // chs={'a', 'b', 'c', 'd', 'e'}

去掉空格:

        String trim()  // 去除字符串两端的空格

字符串分割:

        String[] split(String str)

StringBuilder常用功能:

字符串拼接:

        StringBuilder append(任意类型)

字符串反转:

        StringBuilder reverse()

类型转换:

        String toString(StringBuilder sb)
        StringBuilder(String s)  // String转换为StringBuilder

Demo:

字符串反转:

        String s="abcde";
        StringBuilder sb = new StringBuilder(s);
        sb.reverse();
        s = sb.toString();  // s="edcba"

判断对称字符串

        String s="abcba";
        StringBuilder sb = new StringBuilder(s);
        sb.reverse();
        boolearn = s.equals(sb.toString); //true
点赞