2016/4/27

Java:字串

在Java中,字串是java.lang.String實例,用來包裹字元陣列,你可以用""包括一串字元來建立字串:

String name = "justin"; // 建立String實例,也就是宣告啦
System.out.println(name); // 顯示justin
System.out.println(name.length()); // 顯示長度為6
System.out.println(name.charAt(0)); // 顯示第一個字元j
System.out.println(name.toUpperCase()); // 顯示JUSTIN,小寫轉大寫



用字元陣列來建構String實例:

char[] cs = {'j', 'u', 's', 't', 'i', 'n'};
String name = new String(cs);

也可以把它轉回字元陣列:

char[] cs2 = name.toCharArray();



用+來串接字串

String name = "Justin";
System.out.println("你的名字是:" + name);



字串轉換為整數、浮點數等基本型態:

方法說明
Byte.parseByte(number)將number剖析為byte整數
Short.parseShort(number)將number為short整數
Integer.parseInt(number)將number為int整數
Long.parseLong(number)將number為long整數
Float.parseFloat(number)將number為float浮點數
Double.parseDouble(number)將number剖析為double浮點數

有時有些數字是以字串的方式儲存,如"123"、"3.14"等,如要做運算要把它轉成整數或小數,下面是個範例:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17


package cc.openhome;

import java.util.Scanner;

public class Sum {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long sum = 0;
        long number = 0;
        do {
            System.out.print("輸入數字:");
            number = Long.parseLong(scanner.nextLine());
            sum += number;
        } while(number != 0);
        System.out.println("總合:" + sum);
    }}


下面結果是?

char[] name = {'J', 'u', 's', 't', 'i', 'n'};
String name1 = new String(name);
String name2 = new String(name);
System.out.println(name1 == name2);

反白看答案:

當然是false

String name1 = "Justin";
String name2 = "Justin";
System.out.println(name1 == name2);

是true不多說,因為不比較物件

String name1 = "Justin";
String name2 = "Justin";
String name3 = new String("Justin");
String name4 = new String("Justin");
System.out.println(name1.equals(name2));
System.out.println(name1.equals(name3));
System.out.println(name3.equals(name4));

重點還是,如要比較物件的實質內容,請用equals()



String、StringBuilder、StringBuffer

StringBuilder與StringBuffer是進階處理字串的類別,它可以做到與String同樣的事如字串串接

範例1:

StringBuilder builder = new StringBuilder();

builder.append("測試");

builder.append("字串");

System.out.println(builder.toString());

輸出:測試字串

範例2:

String s = "Java";
String s1 = (new StringBuilder()).append(s).append("World").toString();
System.out.println(s1);

輸出:JavaWorld



就效能來說:StringBuilder > StringBuffer > String

而StringBuffer是Thread-save,StringBuilder 則不是


Java API:
trim():去除String物件前後的空白字元

沒有留言:

張貼留言