Java Basics Part 13/20 - Strings Class

Java Basics Part 13/20 - Strings Class

目錄


在 Java 程序中被廣泛使用的 Strings,也就是字符串,本質上是 一串字符序列。在 Java 中,strings 是對象。
Java 平臺提供了 String 類來創建和操作 strings。


創建 Strings

最直接的方法:

String greeting = "Hello World!";

同樣,既然 strings 是對象,那麼就可以使用 new 關鍵字和構造器來創建一個 String 對象。

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 );
   }
}

// output
hello.

String 類是不可變的,一旦創建無法改變。如果需要對 字符串 做很大的修改,那麼應該使用 StringBuffer 和 StringBuilder 類(StringBuffer 線程安全,所以效率也就更低)。


字符串長度

length() 會返回字符串的長度。

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 );
   }
}

// output
String Length is : 17

連接字符串

可以使用 concat() 方法,也可以使用 + 操作符。


創建格式化的字符串

可以使用 format() 來創建格式化的字符串,返回的是一個 String 對象,而不是 PrintStream 對象。

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 的方法

請參考 Java Doc 中的 String API。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章