java中String类的用法

String类很常用,很重要。
String不像int或float, 它是参考类型。final类型, 不能被继承,String is a Reference Type,Defined in java.lang package
马克- to-win:马克 java社区:防盗版实名手机尾号: 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()翻转字符串
        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表示字符串常量:一旦创建后不会再做修改和变动的字符 串。之所以采用这种方法是因为实现固定的,不可变的字符串比实现可变的字符串更简单高效。对于那些想得到改变的字符串的情况,有一个叫做 StringBuffer的String类的友类。它的对象包含了在创建之后可被改变的字符串。String类和StringBuffer类都在 java.lang包中定义。