[Java] 编程思想 - 字符串

avatarplhDigital nomad

Java字符串的拼接

下面是一段java字符串拼接代码

public class Conversation {
    public static String implicit(String[] fields) {
        String result = "";
        for(int i = 0; i < fields.length; i++) {
            result += fields[i];
        }
        return result;
    }

    public String explicit(String[] fields) {
        StringBuilder result = new StringBuilder();
        for(int i = 0; i < fields.length; i++) {
            result.append(fields[i]);
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String mango = "mango";
        String s = "abc" + mango + "def" + 47;
        System.out.println(s);
        String res = implicit(new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"});
        System.out.println(res);
    }
}

可以通过javap -c拿到java机器代码,可以看到,下面的代码,java拼接就是单纯拼接,并没用到stringBuilder, 而用java stringBuilder来拼接代码,可以看到全文只生成一个stringBuilder.

Compiled from "Conversation.java"
public class Conversation {
  public Conversation();
    Code:
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: return

  public static java.lang.String implicit(java.lang.String[]);
    Code:
         0: ldc           #7                  // String
         2: astore_1
         3: iconst_0
         4: istore_2
         5: iload_2
         6: aload_0
         7: arraylength
         8: if_icmpge     27
        11: aload_1
        12: aload_0
        13: iload_2
        14: aaload
        15: invokedynamic #9,  0              // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
        20: astore_1
        21: iinc          2, 1
        24: goto          5
        27: aload_1
        28: areturn

  public java.lang.String explicit(java.lang.String[]);
    Code:
         0: new           #13                 // class java/lang/StringBuilder
         3: dup
         4: invokespecial #15                 // Method java/lang/StringBuilder."<init>":()V
         7: astore_2
         8: iconst_0
         9: istore_3
        10: iload_3
        11: aload_1
        12: arraylength
        13: if_icmpge     30
        16: aload_2
        17: aload_1
        18: iload_3
        19: aaload
        20: invokevirtual #16                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
        23: pop
        24: iinc          3, 1
        27: goto          10
        30: aload_2
        31: invokevirtual #20                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
        34: areturn

  public static void main(java.lang.String[]);
    Code:
         0: ldc           #24                 // String mango
         2: astore_1
         3: aload_1
         4: invokedynamic #26,  0             // InvokeDynamic #1:makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String;
         9: astore_2
        10: getstatic     #29                 // Field java/lang/System.out:Ljava/io/PrintStream;
        13: aload_2
        14: invokevirtual #35                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
        17: iconst_3
        18: anewarray     #41                 // class java/lang/String
        21: dup
        22: iconst_0
        23: ldc           #43                 // String a
        25: aastore
        26: dup
        27: iconst_1
        28: ldc           #45                 // String b
        30: aastore
        31: dup
        32: iconst_2
        33: ldc           #47                 // String c
        35: aastore
        36: invokestatic  #49                 // Method implicit:([Ljava/lang/String;)Ljava/lang/String;
        39: astore_3
        40: getstatic     #29                 // Field java/lang/System.out:Ljava/io/PrintStream;
        43: aload_3
        44: invokevirtual #35                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
        47: return
}

格式化符号

public class Receipt {
    private double total = 0;
    private Formatter f = new Formatter(System.out);

    public void printTitle() {
        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();
    }
}

输出如下

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

字符串正则

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) {
        split(" ");
        split("\\W+");
        split("n\\W+");
    }
}
[Then,, when, you, have, found, the, shrubbery,, you, must, cut, down, the, mightiest, tree, in, the, forest..., with..., a, herring!]
[Then, when, you, have, found, the, shrubbery, you, must, cut, down, the, mightiest, tree, in, the, forest, with, a, herring]
[The, whe, you have found the shrubbery, you must cut dow, the mightiest tree i, the forest... with... a herring!]