java中String类的用法

1.String

String类很常用,很重要。 

String不像int或float, 它是参考类型。final类型, 不能被继承,String is a Reference Type,Defined in java.lang package

常用方法:
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));
    }
}
 

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

    }
}

String表示字符串常量:一旦创建后不会再做修改和变动的字符 串。之所以采用这种方法是因为实现固定的,不可变的字符串比实现可变的字符串更简单高效。对于那些想得到改变的字符串的情况,有一个叫做 StringBuffer的String类的友类。它的对象包含了在创建之后可被改变的字符串。String类和StringBuffer类都在 java.lang包中定义。

更多请见:http://www.mark-to-win.com/tutorial/java_2_String.html

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值