標籤:rom int als tar poi void 部分 對象 組成
1. 代碼點與代碼單元 Java字串由char序列組成。大多數的常用Unicode字元使用一個代碼單元就可以表示,而輔助字元需要一對代碼單元表示。 length()方法將返回採用UTF-16編碼錶示的給定字串所需要的代碼單元數量 要想的到實際的長度,即代碼點數量 int cpCount = str.codePointCount(0.str.length()) 調用str.charAt(n)將返回位置n的代碼單元,n介於0-str.length()-1之間 要想得到第i個代碼點 int index = str.offsetByCodePoints(0,i); int cp = str.codePointAt(index); 2. 字串APIchar charAt (int index)返回給定位置的代碼單元。除非對底層的代碼單元感興趣,否則不需要調用這個方法 int codePointAt(int index) 5.0返回從給定位置開始或結束的代碼點 int offsetByCodePoints(int startIndex,int cpCount) 5.0返回從startIndex代碼點開始,位移cpCount後的代碼點索引 int compareTo(String other)按照字典順序,如果字串位於other之前,返回一個負數;如果字串位於other之後,返回一個正數;如果兩個字串相等,返回0 boolean endsWith(String suffix)如果字串以suffix結尾,返回true boolean equals(Object other)如果字串與other相等,返回true Boolean equalsIgnoreCase(String other)如果字串與other相等(忽略大小寫),返回true int indexOf(String str)int indexOf(String str,int fromIndex)int indexOf(int cp)int indexOf(int cp,int fromIndex)返回與字串str或代碼點cp匹配的第一個子串開始位置。這個位置從索引0或fromIndex開始計算。如果原始串中不存在str,返回-1 int lastIndexOf(String str)int lastIndexOf(String str,int fromIndex)int lastIndexOf(int cp)int lastIndexOf(int cp,int fromIndex)返回與字串str或代碼點cp匹配的最後一個子串的開始位置。這個位置從原始串尾端或fromIndex開始計算。 int length()返回字串的長度 int codePointCount(int startIndex,int endIndex) 5.0返回startIndex和endIndex – 1之間的代碼點數量。沒有配成對的代用字元將計入代碼點 String replace(CharSequence oldString,CharSequence newString)返回一個新字串,這個字串用newString代替原始字串中所有的oldString。可以用String和StringBuilder對象作為CharSequence參數。 Boolean startsWith(String prefix)如果字串以prefix字串開始,返回true String substring(int beginIndex)String substring(int beginIndex,int endIndex)返回一個新字串。這個字串包含原始字串中從beginIndex到串尾或endIndex-1的所有代碼單元。 String toLowerCase()返回一個新字串。這個字串將原始字串中的所有大寫字母改成了小寫字母。 String toUpperCase()返回一個新字串。這個字串將原始字串中的所有小寫字母改成了大寫字母。 String trim()返回一個新字串。這個字串將刪除原始字串頭部和尾部的空格。 閱讀聯機API文檔,下載JDK api 還有很多String API 3. 構建字串 每次連接字串,都會構建一個新的String對象,既耗時,又浪費空間。使用StringBuilder類就可以避免這個問題的發生。 如果需要用許多小段的字串構建一個字串,那麼應該按照
下列步驟進行。 1、 首先,
構建一個空的字串構建器。 StringBuilder builder = new StringBuilder(); 2、當每次需要添加一部分內容時,就
調用append()方法 builder.append(ch); //append a single character builder.append(str); //append a string 3、在需要構建字串時就
調用ToString方法,將可以得到一個String對象,其中包含了構建器中的字元序列。 String completedString = builder.toString();
StringBuilder的前身是StringBuffer,其效率稍有些低,但允許採用多線程的方式執行添加或刪除字元的操作。如果所有字串在一個單線程中編輯,則應該用StringBuilder替代它。
StringBuilder%StringBuffer API
這兩個類的API是相同的。 StringBuilder()構造一個空的字串構建器 int length()返回構建器或緩衝器中的代碼單元數量 StringBuilder append(Strigng str)追加一個字串並返回this StringBuilder append(char c)追加一個代碼單元並返回this StringBuilder appendCodePoint(int cp)追加一個代碼點,並將其轉換為一個或兩個代碼單元並返回this void setCharAt(int i,char c)將第i個代碼單元設定為c StringBuilder insert(int offset,String str)在offset位置插入一個字串並返回this StringBuilder delete(int startIndex,int endIndex)刪除位移量從startIndex到endIndex-1的代碼單元並返回this String toString()返回一個與構建器或緩衝器內容相同的字串
Java基礎文法<二> 字串String