1. 程式人生 > >String的初步理解

String的初步理解

關於String類的定義和使用

1.

        String str1 = new String("hello");
        String str2 = "hello";
        String str3 = "he"+new String("llo");
        String str4 = "he"+"llo";
        char[] array = {'h','e','l','l','o'};
        String str5 = new String(array);

在這裡插入圖片描述str1在棧中new了一個新的String;
jdk1.6之前,常量池在方法區
jdk1.7之後,常量池在堆裡面
str2 “hello”放在常量池中;
str3實際是new了一個“llo”的String,然後將he連線起來;
str4因為前面的常量池中已經有“hello”了,所以直接指向常量池中的地址;
str5建立new了一個String,只不過裡面存的是char型別的陣列;

2.String中的方法:

  1. public int length()//返回該字串的長度
 String str = new String("abcdefg");
 int strlength = str.length();//strlength = 7

  1. public char charAt(int index)//求字串某一位置字元
    提取子串:
    1)public String substring(int beginIndex)//該方法從beginIndex位置起,從當前字串中取出剩餘 的字元作為一個新的字串返回。
    2)public String substring(int beginIndex, int endIndex)//該方法從beginIndex位置起,從當前字 符串中取出到endIndex-1位置的字元作為一個新的字串返回。
 String str1 = new String("abcdefg");
 String str2 = str1.substring(2);//str2 = "cdefg"
 String str3 = str1.substring(2,5);//str3 = "cde"
  1. public boolean equals(Object anotherObject)//比較當前字串和引數字串
 String str1 = new String("abc");
 String str2 = new String("ABC");
 boolean c = str1.equals(str2);//c=false
  1. 字串中單個字元查詢
    1)public int indexOf(int ch/String str)//用於查詢當前字串中字元或子串,返回字元或子串在當前字串中從左邊起首次出現的位置,若沒有出現則返回-1。
    2)public int lastIndexOf(int ch/String str)//該方法與第一種類似,區別在於該方法從字串末尾位置向前查詢。
 String str = "I am a good student";
int a = str.indexOf('a');//a = 2
 int b = str.indexOf("good");//b = 7
 int c = str.indexOf("w",2);//c = -1
int d = str.lastIndexOf("a");//d = 5
 int e = str.lastIndexOf("a",3);//e = 2
  1. String[] split(String str)//將str作為分隔符進行字串分解,分解後的字字串在字串陣列中返回。
String str = "asd!qwe|zxc#";
String[] str1 = str.split("!|#");//str1[0] = "asd";str1[1] = "qwe";str1[2] = "zxc";
String str3="I am student";
String[] str4=str3.split(" ");//str4[0]="I";str4[1]="am";str4[2]="student";
  1. getChars() 方法從這個字串中的字元複製到目標字元陣列
    //底層呼叫的System.arraycopy
  2. intern():如果在常量池當中沒有字串的引用,那麼就會生成一個在常量池當中的引 用,相反則不生成。
    //本地方法

3.String 和StringBuffer 和StringBuilder 比較

在執行速度上:Stringbuilder->Stringbuffer->String
String是字串常量
String 類 是不可變類,不能試圖去修改它的值
public final class String
final 定義的 一次賦值,不可修改
 Stringbuffer是字串變數  Stringbuilder是字串變數
StringBuffer:  synchronized執行緒安全  多執行緒
StringBuilder:  單執行緒