Java String類
Java中,字元串屬于對象。
Java提供了String類來建立和操作字元串。
建立字元串
建立字元串最簡單方式:
String str = "Hello World!"
使用關鍵字和構造方法來建立String對象。
String類有11種構造方法,這些方法提供不同的參數來初始化字元串,比如提供一個字元數組參數:
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString )
運作結果如下:
hello.
注意:String類是不可改變的,一旦建立了String對象,那它的值就無法改變了。如果需要對字元串做很多修改,那麼應該選擇使用StringBuffer & StringBuilder類。
字元串長度
用于擷取有關對象的資訊的方法稱為通路器方法。
String類的的一個通路器方法是length()方法,它傳回字元串對象包含的字元數。
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
運作結果為:
String Length is :17
連接配接字元串
String 類提供了連接配接兩個字元串的方法:
string.concat(string2);
傳回string2連接配接string1的新字元串。
也可對字元串常量使用concat()方法,如:
“my name is ”.concat("Alary");
更常用的是使用 ‘+’ 操作符來連接配接字元串,如:
"hello," + "world" + "!";
運作結果為:
hello,world!
建立格式化字元串
輸出格式化數字可以使用printf()和format(0方法。
String類使用靜态方法format()傳回一個String對象而不是PrintStream對象。
String類的靜态方法format()能用來建立可服用的格式化字元串,而不僅僅是用于一次列印輸出。
執行個體:
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
也可以這樣寫:
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);