1. String和StringBulider的使用
通过书中介绍, 我们得知如下结论:
总结: 当字符串操作比较简单(没有for循环等)时,可以依赖编译器进行优化。 但是如果这个字符串需要使用for循环,那么最好自己创建一个StringBuilder对象,用它来构造最终的结果。
注意: 在使用StringBuilder的时候, 要避免这样写:append( a + ":" + c),这样编译器依然要先处理内部的字符串。这个字符串处理也是创建一个Stringbuilder来处理的。
2. 无意识的递归
这里无意识的递归指的是. 在toString方法中, 想要显示对象的内存地址. 不能使用this, 而要使用super.toString(). 使用this会导致无线循环. 为什么使用this会导致无限循环呢?看下面的代码中的注释就知道了.
package net.mindview.strings;
import java.util.ArrayList;
import java.util.List;
/**
* 无限循环
*/
public class InfiniteRecursion {
public InfiniteRecursion(){
}
@Override
public String toString() {
/*
* 使用this会导致无限循环,为什么呢?
* 因为: this前面是一个字符串,后面跟着+,就会想到将this转换为字符串,
* 结果转换成字符串就有调用本身的toString方法了, 导致了无限循环
*/
return " InfiniteRecursion address" + this + "\n";
//return " InfiniteRecursion address" + super.toString() + "\n";
}
public static void main(String[] args) {
List<InfiniteRecursion> list = new ArrayList<InfiniteRecursion>();
for(int i=0; i<5; i++){
list.add(new InfiniteRecursion());
}
System.out.println(list);
}
}
正确的做法是将注释行去掉. 使用super.toString()
3. 格式化输出
格式化输出使用System.out.printf() 或者System.out.format();
package net.mindview.strings;
public class SimpleFormat {
public static void main(String[] args) {
int x = 5;
double y = 5.332542;
System.out.println("Row 1: [" + x + " " + y + "]");
//一下两种方式是等价的.
System.out.format("Row 1: [%d %f]\n", x, y);
System.out.printf("Row 1: [%d %f]\n", x, y);
}
}
所有新的格式化功能,都有java.util.Formatter类处理。使用Formatter对象的时候,需要向其构造器传递信息,告诉Formatter,最终的结果输出到哪里。
package net.mindview.strings;
import java.io.PrintStream;
import java.util.Formatter;
public class Turtle {
private String name;
private Formatter f;
public Turtle(String name, Formatter f){
this.name = name;
this.f = f;
}
public void move(int x, int y){
f.format("%s The Turtle is at (%d.%d)\n", name, x, y);
}
public static void main(String[] args) {
PrintStream outAlias = System.out;
Turtle tommy = new Turtle("Tommy", new Formatter(System.out));
Turtle terry = new Turtle("Terry", new Formatter(outAlias));
tommy.move(0, 0);
terry.move(4, 8);
tommy.move(3, 4);
terry.move(2, 5);
tommy.move(3, 3);
terry.move(3, 3);
}
}
总结:
语法: %[argument_index$][flags][width][.precision]conversion
格式化操作符以%开头,
含义:
Item Qty Price
---- --- -----
Jack`s Magic Be 4 4.25
Princess Peas 3 5.10
Three Bears Por 1 14.29
Tax 1.42
-----
Total 25.06
package net.mindview.strings;
import java.util.Formatter;
public class Receipt {
private double total = 0;
private Formatter f = new Formatter(System.out);
//打印标题
public void printTitle(){
/*
* 含义: 格式化字符串串以%开头
* -: 表示左对齐
* 15: 15表示宽度
* s:表示数据的类型是String
* .2:表示保留的小数位数
*/
f.format("%-15s %5s %10s\n", "Item", "Qty", "Price");
f.format("%-15s %5s %10s\n", "----", "---", "-----");
}
//正文的内容
public void print(String name, int qty, double price){
f.format("%-15.15s %5d %10.2f\n", name, qty, price);
total += price;
}
//总价
public void printTotal(){
f.format("%-15s %5s %10.2f\n", "Tax", "", total*0.06);
f.format("%-15s %5s %10s\n", "", "", "-----");
f.format("%-15s %5s %10.2f\n", "Total", "", total*1.06);
}
public static void main(String[] args) {
Receipt receipt = new Receipt();
receipt.printTitle();
receipt.print("Jack`s Magic Beans", 4, 4.25);
receipt.print("Princess Peas", 3, 5.1);
receipt.print("Three Bears Porridge", 1, 14.29);
receipt.printTotal();
}
}
String.format()方法是一个static方法,他接受与Formatter。format()方法一样的参数。返回值是一个String。
4. 正则表达式
直入主题
package net.mindview.strings;
public class IntegerMatch {
public static void main(String[] args) {
System.out.println("-1234".matches("-?\\d+"));
System.out.println("5678".matches("-?\\d+"));
System.out.println("+991".matches("-?\\d+"));
System.out.println("+911".matches("(-|\\+)?\\d+"));
}
}
package net.mindview.strings;
import java.util.Arrays;
public class Splitting {
public static String knights = "Then, when you have found the shrubbery, you must cut down the mightiest tree in the forest... with... a herring!";
public static void split(String regex){
System.out.println(Arrays.toString(knights.split(regex)));
}
public static void main(String[] args) {
//表示的时按照空格分割字符串
//运行结果:[Then,, when, you, have, found, the, shrubbery,, you, must, cut, down, the, mightiest, tree, in, the, forest..., with..., a, herring!]
split(" ");
//表示按照非单次字符分割字符串--这里的非单次字符是空格和,
//运行结果:[Then, when, you, have, found, the, shrubbery, you, must, cut, down, the, mightiest, tree, in, the, forest, with, a, herring]
split("\\W+");
//这个表示:费单次字符之前带n的地方进行分割字符串 这里的分割符是n空格和n,
//运行结果:[The, whe, you have found the shrubbery, you must cut dow, the mightiest tree i, the forest... with... a herring!]
split("n\\W+");
}
}
package net.mindview.strings;
public class Replacing {
static String s = Splitting.knights;
public static void main(String[] args) {
System.out.println(s.replaceFirst("f\\w+", "located"));
System.out.println(s.replaceAll("shrubbery|tree|herring", "banana"));
}
}
Input: "abcabcabcdefabc"
Regular expression: "abcabcabcdefabc"
Match "abcabcabcdefabc" at positions 0-14
Regular expression: "abc+"
Match "abc" at positions 0-2
Match "abc" at positions 3-5
Match "abc" at positions 6-8
Match "abc" at positions 12-14
Regular expression: "(abc)+"
Match "abcabcabc" at positions 0-8
Match "abc" at positions 12-14
Regular expression: "(abc){2,}"
Match "abcabcabc" at positions 0-8
package net.mindview.strings;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegularExpression {
public static void main(String[] args) {
if(args.length < 2){
System.out.println("Usage:\njava TestRegularExpression "+"characterSequence regularExpression+");
System.exit(0);
}
System.out.println("Input: \""+ args[0] + "\"");
for(String arg: args){
System.out.println("Regular expression: \"" + arg +"\"");
//定义一个正则表达式的类对象
Pattern p = Pattern.compile(arg);
//使用正则表达式匹配字符串.
Matcher m = p.matcher(args[0]);
//对匹配到的字符串进行处理.
while(m.find()){
System.out.println("Match \"" + m.group() +"\" at positions " + m.start() + "-" + (m.end()-1) );
}
System.out.println("\n\n");
}
}
}