首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

String的步骤使用

2012-08-21 
String的方法使用1. split()根据特定字符,把一个字符串分解成n个部分。有两种形式:split(String regex)spl

String的方法使用
1. split()

根据特定字符,把一个字符串分解成n个部分。

有两种形式:

split(String regex);split(String regex, int limit);


split(String regex)会调用split(regex, 0)方法

limit控制着分解的次数,所以对结果有影响:

a. 如果limit是正数,分解最多(limit - 1)次

b. 如果limit是负数,分解次数没有限制

c. 如果limit是0,分解次数没有限制,但是会去除结果尾部空的部分

举例:

String szToSplit = ",0,1,2,3,4,5,6,7,8,9,,";String[] arrSplited0 = szToSplit.split(",");String[] arrSplitedA = szToSplit.split(",", 4);String[] arrSplitedB = szToSplit.split(",", -1);String[] arrSplitedC = szToSplit.split(",", 0);


结果:
arrSplited0: [, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
arrSplitedA: [, 0, 1, 2,3,4,5,6,7,8,9,,]
arrSplitedB: [, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, , ]
arrSplitedC: [, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2. String是一个常量

String是不可被改变的,一旦创建某个String,其它地方只需对它进行引用; 通过new String(String str)方式会创建一个新的String对象:

String heaven1 = "paradise";String heaven2 = "paradise";String heaven3 = new String("paradise");System.out.println(heaven1 == heaven2); // trueSystem.out.println(heaven1 == heaven3); // false


如果是两个或两个以上的字符串组合,编译器会对它们进行优化,组成一个字符串,效果和上面相同:

String heaven4 = "discriminator" + "paradise";String heaven5 = "discriminator" + "paradise";System.out.println(heaven4 == heaven5); // true


但是运行时才知道的String除外:
public class StringParadise {private String key;private String value;// Getters and setters are omittedpublic StringParadise(String key1, String key2, String value) {this.key = key1 + key2;this.value = value;}public static void main(String[] args) {StringParadise test1 = new StringParadise("a", "", "paradise");StringParadise test2 = new StringParadise("a", "", "heaven");System.out.println(test1.getKey() == test2.getKey()); // false}}


3. intern()
该方法返回一个字符串对象的内部化引用。

String类维护一个初始为空的字符串的对象池,当intern方法被调用时,如果对象池中已经包含这一个相等的字符串对象则返回对象池中的实例,否则添加字符串到对象池并返回该字符串的引用。

String szCanonicalA = "Hello, Inteference";String szCanonicalB = "Hello, " + "Inteference";System.out.println(szCanonicalA == szCanonicalB); // trueSystem.out.println(szCanonicalA.intern() == szCanonicalB.intern()); // true


szCanonicalA和szCanonicalB都是常量(szCanonicalB的值会被编译时候被优化)

4. concat()

把指定的字符串附加到当前字符串的末尾。

public String concat(String str) {int otherLen = str.length();if (otherLen == 0) {return this;}char buf[] = new char[count + otherLen]; // 实例化字符数组getChars(0, count, buf, 0); // 把当前字符串的字符序列放到数组上str.getChars(0, otherLen, buf, count); // 把参数字符串的字符序列附加到数组上return new String(0, count + otherLen, buf); // 构建新的字符串}


和strA + strB相比,strA.concat(strB)一定程序上提升了性能。

热点排行