第13章 字符串
1、String对象默认为不可变的,因此任何貌似对String的改变本质都是创建一个新的String对象,并返回它的引用。
2、在构建String对象时,由于不断地产生中间的String对象,这样效率极低,因此建议使用StringBuider对象。
//: strings/UsingStringBulider.java
import java.util.*;
public class UsingStringBulider{
public static Random rand = new Random(47);
public String toString(){
StringBuilder result = new StringBuilder("[");
for(int i=0; i<25; i++){
result.append(rand.nextInt(100));
result.append(", ");
}
result.delete(result.length()-2, result.length());
result.append("]");
return result.toString();
}
public static void main(String[] args){
UsingStringBulider usb = new UsingStringBulider();
System.out.println(usb);
}
}/*Output
[58, 55, 93, 61, 61, 29, 68, 0, 22, 7, 88, 28, 51, 89, 9, 78, 98, 61, 20, 58, 16, 40, 11, 22, 4]
*///:~
3、格式化输出
System.out.format("Row 1: [%d %f]\n", x, y);
System.out.printf("Row 1: [%d %f]\n", x, y);
String str = String.format("Row 1: [%d %f]\n", x, y);
特殊格式实现
标 志 | 说 明 | 示 例 | 结 果 |
+ | 为正数或者负数添加符号 | ("%+d",15) | +15 |
− | 左对齐 | ("%-5d",15) | |15 | |
0 | 数字前面补0 | ("%04d", 99) | 0099 |
空格 | 在整数之前添加指定数量的空格 | ("% 4d", 99) | | 99| |
, | 以“,”对数字分组 | ("%,f", 9999.99) | 9,999.990000 |
( | 使用括号包含负数 | ("%(f", -99.99) | (99.990000) |
# | 如果是浮点数则包含小数点,如果是16进制或8进制则添加0x或0 | ("%#x", 99) ("%#o", 99) | 0x63 0143 |
< | 格式化前一个转换符所描述的参数 | ("%f和%<3.2f", 99.45) | 99.450000和99.45 |
$ | 被格式化的参数索引 | ("%1$d,%2$s", 99,"abc") | 99,abc |
4、正则表达式
import static java.lang.System.out;
// out is a method, but it returns a class which has a println method
import java.util.*;
import java.util.regex.*;
public class IntegerMatch{
public static void main(String[] args){
// begin with a capital letter and end with a period
out.println("This is a test.".matches("^[A-Z].*\\.$"));
// split with the and you
out.println(Arrays.toString("This is the goal, you must do better.".split("the|you")));
// replace all vowels with underline
out.println("This is the goal, you must do better.".replaceAll("[aeiou]","_"));
String s = "Java now has regular expressions";
String regex = "n.w\\s+h(a|i)s";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while(m.find())
out.println("Match \"" + m.group() + "\" at positions " + m.start() + "-" + (m.end() - 1));
String str = "Arline ate eight apples and one orange while Anita hadn't any";
String regex2 = "(?i)((^[aeiou])|(\\s+[aeiou]))\\w+?[aeiou]\\b"; // (?i): Case insensitivity
Pattern p2 = Pattern.compile(regex2);
Matcher m2 = p2.matcher(str);
while(m2.find())
out.println("Match \"" + m2.group() + "\" at positions " + m2.start() + "-" + (m2.end() - 1));
}
}/* Output
true
[This is , goal, , must do better.]
Th_s _s th_ g__l, y__ m_st d_ b_tt_r.
Match "now has" at positions 5-11
Match "Arline" at positions 0-5
Match " ate" at positions 6-9
Match " one" at positions 27-30
Match " orange" at positions 31-37
Match " Anita" at positions 44-49
*///:~
5、每一个非基本类型的对象都有一个toString()方法,而且当编译器需要一个String而却只有一个对象时,该方法便会被调用。