十四、300份Java零基礎教學筆記,真正的從零開始(關注持續更新)

Java快速入門(本文篇幅較長,建議點喜歡後收藏後閱讀)
每天學會一個知識點,覺得不錯的可以留言關注下,戳我主頁獲取Java資料(工具包,面試資料,視頻教學,包含社羣解答)

Java String類

字符串廣泛應用在Java編程中,在Java中字符串屬於對象,Java提供了String類來創建和操作字符串。

創建字符串

創建字符串最簡單的方式如下:

String greeting = "Hello world!";

在代碼中遇到字符串常量時,這裏的值是"Hello world!",編譯器會使用該值創建一個String對象。

和其它對象一樣,可以使用關鍵字和構造方法來創建String對象。

String類有11種構造方法,這些方法提供不同的參數來初始化字符串,比如提供一個字符數組參數:

public class StringDemo{

   public static void main(String args[]){
      char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
      String helloString = new String(helloArray);  
      System.out.println( helloString );
   }
}

以上實例編譯運行結果如下:

hello.

注意:String類是不可改變的,所以你一旦創建了String對象,那它的值就無法改變了。 如果需要對字符串做很多修改,那麼應該選擇使用StringBuffer & StringBuilder 類

字符串長度

用於獲取有關對象的信息的方法稱爲訪問器方法。

String類的一個訪問器方法是length()方法,它返回字符串對象包含的字符數。

下面的代碼執行後,len變量等於17:

public class StringDemo {

   public static void main(String args[]) {
      String palindrome = "Dot saw I was Tod";
      int len = palindrome.length();
      System.out.println( "String Length is : " + len );
   }
}

以上實例編譯運行結果如下:

String Length is : 17

連接字符串

String類提供了連接兩個字符串的方法:

string1.concat(string2);

返回string2連接string1的新字符串。也可以對字符串常量使用concat()方法,如:

"My name is ".concat("Zara");

更常用的是使用'+'操作符來連接字符串,如:

"Hello," + " world" + "!"

結果如下:

"Hello, world!"

下面是一個例子:

public class StringDemo {
   public static void main(String args[]) {     
   String string1 = "saw I was ";     
   System.out.println("Dot " + string1 + "Tod");  
}
}

以上實例編譯運行結果如下:

Dot saw I was Tod

創建格式化字符串

我們知道輸出格式化數字可以使用printf()和format()方法。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);

String 方法

下面是String類支持的方法,更多詳細,參看Java API文檔:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章