java中String類的用法

String類很常用,很重要。
String不像int或float, 它是參考類型。final類型, 不能被繼承,String is a Reference Type,Defined in java.lang package
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。



常用方法:
length()
String greeting = “Hello”;
int n = greeting.length();//is 5
charAt(n)(取某個位置字符)
char first = greeting.charAt(0);
char last = greeting.charAt(4);
substring()(取子字符串)
String s = greeting.substring(0,3);//from 0 inclusive to 3 exclusive
Concatenation(鏈接)
String a = greeting + “ world!”+ 2009;
Equality(don’t use ==)(測試是否相等)
String s = “Hello”; s.equals(greeting);
“Hello”.equalsIgnoreCase(“hello”);(忽略大小寫的測試相等)
本章源碼
例子:
public class Test {
    public static void main(String args[]) {
        String letters = "abcdefghijklabcdefghijkl";
/*這里講講閱讀源代碼,control點擊進入方法*/
        System.out.println("'c'在第" + letters.indexOf('c') + "個");
/* indexOf(int ch, int fromIndex) Returns the index within this string
of the first occurrence of the specified character, starting the
search at the specified index.*/
        System.out.println("'a'在第" + letters.indexOf('a', 1) + "個");
        System.out.println("'$'在第" + letters.indexOf('$') + "個");
        System.out.println("def在第" + letters.indexOf("def") + "個");
        System.out.println("'c'在第" + letters.lastIndexOf('c') + "個");
        System.out.println(letters.substring(20));// 從第20個到末尾
/*beginIndex - the beginning index, inclusive(包含). endIndex - the ending
index, exclusive(不包含).*/
        System.out.println(letters.substring(3, 6));
    }
}




result is:

'c'在第2個
'a'在第12個
'$'在第-1個
def在第3個
'c'在第14個
ijkl
def

public class Test {
    public static void main(String args[]) {
        String s, s1;
        char charArray[] = new char[8];
        s1 = new String("Hello World!");
        // s1 = "Hello World!";
        // 輸出String的長度
        System.out.println(s1.length());
        s1=s1.replace("World", "mark-to-win");
        System.out.println("s1 is "+s1);
        // 使用charAt()翻轉(zhuǎn)字符串
        s = "";
        for (int i = s1.length() - 1; i >= 0; i--)
            s = s + s1.charAt(i);
        System.out.println(s);

    }
}


result is:
12
s1 is Hello mark-to-win!
!niw-ot-kram olleH


String表示字符串常量:一旦創(chuàng)建后不會再做修改和變動的字符 串。之所以采用這種方法是因為實現(xiàn)固定的,不可變的字符串比實現(xiàn)可變的字符串更簡單高效。對于那些想得到改變的字符串的情況,有一個叫做 StringBuffer的String類的友類。它的對象包含了在創(chuàng)建之后可被改變的字符串。String類和StringBuffer類都在 java.lang包中定義。