- 轉換(transform)-魔形女
- 比較(compare)
- 子集合(subset)
- 分割(split)-次元刀
- 合併(join)
Some Data Type -> String
Integer -> String
1 2 3 4 5 6 7 8 9 10
| int number = 1234;
String.valueOf(number)
Integer.toString(number)
"" + number
|
char -> String
1 2
| char c = '0'; String.valueOf(char);
|
int Array -> String
1 2 3
| int[] array = {1,2,3,4}; String strArr = Arrays.toString(array);
|
byte Array -> String
1 2
| String testString = new String(bytes, StandardCharsets.UTF_8);
|
String -> Some Data Type
Some Data Type: int, long, BigInteger, BigDecimal, double, byte[], char[]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| String number = "1234"; String bigDecimal = "1234.5678"; String doubleN = "3.14";
int intNum = Integer.parseInt(number);
long longNum = Long.parseLong(number);
BigInteger bigIntegerNum = new BigInteger(number);
BigDecimal bigDecimalNum = new BigDecimal(bigDecimal);
double doubleNum = Double.parseDouble(doubleN);
|
1 2
| byte[] bytes = "1234".getBytes(StandardCharsets.UTF_8);
|
1 2 3 4 5 6
| String s = "1234"; char[] charArray = s.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);
|
1 2 3 4 5 6 7
| String pokemon = "Bulbasaur,Charmander,Squirtle,Pikachu"; String[] pokemons = pokemon.split(","); List<String> pokemonList = Arrays.asList(pokemons);
List<String> pokemonList2 = new ArrayList<String>(Arrays.asList(pokemons));
|
比較(compare)
equals
, equalsIgnoreCase
, compareTo
, compareToIgnoreCase
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| String str1 = "abc"; String str2 = new String("abc"); String str3 = new String("aBc");
str1.equals(str2)
str1.equals(str3)
str2.equals(str3)
str1.compareTo(str2)
str2.compareTo(str3)
str3.compareTo(str2)
|
子集合(subset)
substring
, 使用開始(beginIndex)與結束標記(endIndex)取得不包含結束標記的子字串。
1 2 3 4 5 6 7
| String str1 = new String("0123456789");
str1.substring(5)
str1.substring(5, 9)
|
分割(split)-次元刀
split
或 StringTokenizer
,注意escape character
split
1 2 3 4 5 6 7
| String pokemon = "Bulbasaur,Charmander,Squirtle,Pikachu"; String[] pokemons = pokemon.split(",");
String pokemonCP = "Bulbasaur235Charmander167Squirtle3310Pikachu9527";
String[] pokemons = pokemonCP.split("\\d+");
|
StringTokenizer
1 2 3 4 5 6
| String pokemon = "Bulbasaur Charmander Squirtle Pikachu"; StringTokenizer tokenizer = new StringTokenizer(pokemon); while (tokenizer.hasMoreTokens()) { System.out.println(tokenizer.nextToken()); }
|
合併(join)
+
,String的concat
, StringBuffer或StringBuilder的append
延伸議題:StringBuilder vs String concatenation in toString() in Java
1 2 3 4 5 6 7 8 9
| String str1 = "Pikachu is"; String str2 = " cute";
str1 = str1.concat(str2);
StringBuilder sb = new StringBuilder(); sb.append(str1); sb.append(str2); sb.toString();
|