String类的常用操作

1.charAt(int index)

        String s = "1234567890";
        System.out.println(s.charAt(1));      //2

2.compareTo(String anotherString)

        String s1 = "1234567870";
        String s2 = "12345678";
        String s3 = "1234567891";
        System.out.println(s1.compareTo(s2));  //2 返回长度差
        System.out.println(s1.compareTo(s3));  //-2 返回最前一位不同值的差‘7’-‘9’

3.concat(String str) 与‘+’类似,连接字符串

  1. endsWith(String str) 是否以str结尾
    startsWith(String str)startsWith(String str , int offset)

5.equals(String str) equalsIgnoreCase(String str)判断是否相等

int indexOf(char ch)
int indexOf(char ch ,int fromIndex)
int indexOf(String str)
int indexOf(String str ,int fromIndex)
int lastIndexOf(char ch)
int lastIndexOf(char ch ,int fromIndex)
int lastIndexOf(String str)
int lastIndexOf(String str ,int fromIndex)

        String str = new String("skljfkjklsaaifs");
        System.out.println(str.lastIndexOf('s'));     //14
        System.out.println(str.lastIndexOf('s',10));  //9
length()

replace(char ch1,char ch2)将所有的ch1替换成ch2
replaceAll(String regex,String newstr)
replaceFirst(String regex,String newstr)

String str = new String("a12djhjk7890a");
System.out.println(str.replace('a','q'));          //q12djhjk7890q
System.out.println(str.replaceAll("\\d","q"));     //aqqdjhjkqqqqa
System.out.println(str.replaceFirst("\\d","q"));   //aq2djhjk7890a
  1. String substring(int beginIndex)
    String substring(int beginIndex,int endIndex)返回子字符串

char[] toCharArray()

12.toUpperCase()
toLowerCase()

13.String.valueOf(X x)将其他类型转化为String类型

StringBuffer是线程安全的,StringBuilder是线程不安全的,故性能相对较快。具体的使用可查阅API。

        StringBuilder sb = new StringBuilder();
        sb.append("java");    //sb= "java"
        sb.insert(0,"hello ");  //sb = "hello java"
        sb.replace(5,6,",");//sb = "hello,java"
        sb.delete(5,6);//sb = "hellojava"
        System.out.println(sb);
        sb.reverse();     //sb = "avajolleh"
        System.out.println(sb);
        System.out.println(sb.length());//9
        System.out.println(sb.capacity());//16
        sb.setLength(5);      //sb = "avajo"
        System.out.println(sb);

你可能感兴趣的:(String类的常用操作)