1.鍵盤輸入字符串
使用Scanner
類中的 nextLine()
方法。注意該方法如果與nextInt()
同時使用,會導致字符串無法錄入。因為輸入int數時,數后面會默認帶一個行分割符/r/n
,而nextLine()
方法遇到 /r/n
就會停止錄入。解決方法:數字和字符串都使用 nextLine()
方法輸入,使用時再把數字字符串轉化為數字。
2 .java
對String
類進行了封裝 字符串字面值可以看做一個String對象,字符串是常量,存放于常量池,一經創建就不可以改變。 關于String
類中的" + "
:
The Java language PRovides special support for the string concatenation Operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.
String s = null
與 String s = ""
區別: String s = null
中s
沒有任何對象指向,是一個null常量值。不可調用任何方法。否則會出現空指針異常;String s = ""
中s
指向一個具體的字符串對象,只不過這個字符串中沒有內容,s
可以調用string
方法。
3 .String
類構造方法:將字節數組或者字符數組轉成字符串
舉兩個byte[]
數組的栗子:
(1)String(byte[] bytes)
用平臺默認編碼方式解碼把byte
數組轉化為字符串
(2)String(byte[] bytes, int offset, int length
Constructs a new String by decoding the specified subarray of bytes using the platform’s default charset.用平臺默認編碼方式解碼把byte數組一部分轉化為字符串。offset
為初始索引值,length
為長度。
4 .String
獲取方法:
(1)獲取字符串的長度。length()
(2)指定位置的字符。char charAt(int index)
(3)獲取指定字符的位置。如果不存在返回-1,所以可以通過返回值-1來判斷某一個字符不存在的情況。 int indexOf(int ch) 返回第一次找到的字符index int indexOf(int ch,int fromIndex) 返回從指定位置開始第一次找到的index int indexOf(String str) 返回第一次找到的字符串index int indexOf(String str,int fromIndex) int lastIndexOf(int ch); int lastIndexOf(int ch,int fromIndex); int lastIndexOf(String str); int lastIndexOf(String str,int fromIndex); 以上為從后往前返回相應字符或字符串第一次出現的索引值
(4)截取子串。
String substring(int start)從start位開始,到length()-1為止
String substring(int start,int end)從start開始到end為止,包含start位,不包含end位
substring(0,str.length())
獲取整串
5 .String 類判斷方法:
(1)判斷字符串中包含指定的字符串
boolean contains(String substring)(2)判斷字符串是否以指定字符串開頭
boolean startsWith(string)(3)判斷字符串是否以指定字符串結尾
boolean endsWith(string)(4)判斷判斷字符串是否相同
boolean equals(string)(5)判斷字符串內容是否相同,忽略大小寫。
boolean equalsIgnoreCase(string)(6)判斷字符串是否為空
boolean isEmpty(string)注:String類重寫了Object中的equals方法。如果是字符串常量與字符串變量比較,一般把常量寫在前面,調用equals方法,可以防止空指針異常。
6.String類的轉換:通過構造方法可以將字符數組或者字節數組轉成字符串。
(1)可以通過字符串中的靜態方法,將字符數組轉成字符串。
static String copyValueOf(char[] )static String copyValueOf(char[],int offset,int count);static String valueOf(char[])static String valueOf(char[],int offset,int count)(2)將基本數據類型或者對象轉成字符串。
static String valueOf( )可以傳遞各基本數據類型 char,boolean,double,float,int,long
指的是直接調用對象toString()
方法,如果直接打印對象的引用,系統也會默認添加toString
方法 (3)將字符串轉成大小寫。
(4)將字符串轉成數組。
char[] toCharArray()把字符串轉化字符數組。
byte[] getBytes()把字符串轉成字節數組,利用平臺提供的編碼方式把字符串編譯成為計算機能夠識別的語言;
7.其他
String replace(oldChar,newChar)將字符串中的字符進行內容替換
String replace(oldstring,newstring)將字符串進行內容替換,修改后變成新字符串,并不是將原字符串直接修改 String concat(string)
用于對字符串進行追加 String trim()
用于去除字符串兩端的空格
用于比較兩個字符串字典順序。字典順序:兩個字符串相比不等要么是長度不同,要么是某些對應index
上字符不同,假設k是這樣的最小索引。返回值為this.charAt(k)-anotherString.charAt(k)
;如果這樣也比較不出大小,就直接比較兩個字符串的長度,返回
新聞熱點
疑難解答