一、字元串轉化成數字型
String s = "123.456 "; //要確定字元串為一個數值,否則會出異常
double d = Double.parseDouble(s);
float f = Float.parseFloat(s);
String s = "123 ";
int i = Integer.parseInt(s);
二、數字型轉化成字元串
方法一:直接強制轉換。如:String str= (String)123;
方法二:直接通過空字元串+數字的形式轉換為字元串(前後都可以用)。如:String str= ""+123;
方法三:直接通過包裝類來實作。如:String str = String.valueOf(123456);
三、字元串拆分
String類下的split方法,可以按照指定的定界字元串,對某一字元串進行分割,将待分割字元串中參考字元串前後的字元串提取出來,作為傳回值。傳回類型為String中,次元由分割完成的結果決定,但内容中會直接去掉定界字元串。定界字元串查找不到時傳回結果為該字元串本身。 需要注意的是定界字元串本質上是正規表達式,如果參考字元串中包含有特殊含義的符号,需要進行轉義。
String a = "abcdefgabcdefgabcdefg";
String b[] = a.split("a");
for(inti = 0; i<b.length; i++)
System.out.println(b[i]);
運作結果為:
bcdefg
bcdefg
bcdefg
String a = "abcdefgabcdefgabcdefg";
String b[] = a.split("a",2);
for(int i = 0; i<b.length; i++)
System.out.println(b[i]);
運作結果為:
bcdefgabcdefgabcdefg
即split第二個參數用來限制分割完成的字元串段數,分割由左到右進行,預設則代表分割段數不限,直至分割完成為止。
四、字元串查找
String類下的lastIndexOf方法,用于在目前字元串中查找指定字元串。
1、int lastIndexOf(String arg0) 和 int lastIndexOf(int arg0)
用于查找目前字元串中指定字元串或字元(int arg0表字元的ascii碼值)最後出現的位置,傳回值為子串在原串中的相對位置,若找不到,則傳回-1。
看例子:
String s = "abcdefgabcdefg";
int i = s.lastIndexOf("cd");
System.out.println(i);
運作結果為:
9
需要注意的是字元串s中共有兩個”cd”子串,本函數傳回的是最後一個子串的位置。
2、int lastIndexOf(String arg0, int arg1) 和int lastIndexOf(int arg0, int arg1)
在目前字元串中小于arg1的範圍中,查找指定字元串或字元。傳回值同樣為子串在原串中最後一次出現的相對位置,隻不過查找有範圍限制,超出範圍的部分即便仍有子串,也無法找到。
看例子:
String s = "abcdefgabcdefg";
int i = s.lastIndexOf("cd",8);
System.out.println(i);
運作結果為:
2
注意與上一個例子做比較。
但是當範圍當中包含了子串的前面的某一位或某幾位時:
String s = "abcdefgabcdefg";
int i = s.lastIndexOf("cd",9);
System.out.println(i);
運作結果為:
9
原因很簡單,字元串比較時限制的範圍僅限制住了首位址而沒有限制長度。
與lastIndexOf方法相對的indexOf方法。
1、Int indexOf(String arg0)和Int indexOf(int arg0)
這兩個方法傳回值為源字元串中子串最先出現的位置(參數int arg0同樣指字元的ascii碼值),若找不到,則傳回-1。
與上文lastIndexOf對比:
String s = "abcdefgabcdefg";
int i = s.indexOf("cd");
System.out.println(i);
運作結果為:
2
2、 int indexOf(String arg0, int arg1) 和int indexOf(int arg0, int arg1)
這兩個方法傳回值為從指定位置起查找,子串最先出現的位置,若找不到,則傳回-1。與lastIndexOf相差別的是indexOf的限制arg1參數限定的是由此位起始搜尋,lastIndexOf限定的是搜尋到此位為止。
則:
String s = "abcdefgabcdefg";
int i = s.indexOf("cd",8);
System.out.println(i);
運作結果為:
9
String substring(int arg0)與String substring(int arg0, int arg1)
這兩個函數用來在源字元串中根據指定位置取出子串。前者傳回源字元串中從參數arg0指定的位置開始至字元串結尾的子串;後者傳回源字元串中位置arg0到位置arg1指定的子串。
substring可與上文中的查找方法一起使用,用于提取指定字元串。
看例子:
String s = "abcdefgabcdefg";
String cd = "cd";
String s1 = s.substring(s.indexOf(cd));
String s2 = s.substring(s.indexOf(cd), s.indexOf(cd)+cd.length());
System.out.println(s1);
System.out.println(s2);
運作結果為:
cdefgabcdefg
cd
注意當參數越界時會抛出Java.lang.StringIndexOutOfBoundsException異常。