Cách sử dụng đối tượng StringBuilder

Trong post này:

  • Lấy độ dài StringBuilder
  • Convert StringBuilder to String

1. Lấy độ dài StringBuilder

public class Main {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder(200); // Capacity:200, length:0
    sb.append("Hello"); // Capacity:200, length:5
    int len = sb.length(); // len is assigned 5
    int capacity = sb.capacity(); // capacity is assigned 200
  }
}

2. Convert to String

public class Main {
  public static void main(String[] args) {
    // Create a String object
    String s1 = new String("Hello");
    // Create a StringBuilder from of the String object s1
    StringBuilder sb = new StringBuilder(s1);

    // Append " Java" to the StringBuilder's content
    sb.append(" Java"); // Now, sb contains "Hello Java"

    // Get a String from the StringBuilder
    String s2 = sb.toString(); // s2 contains "Hello Java"

  }
}

public class Main {
  public static void main(String[] args) {
    // Length is 5
    StringBuilder sb = new StringBuilder("Hello");

    // Now the length is 7 with last two characters as null character '\u0000'
    sb.setLength(7);

    // Now the length is 2 and the content is "He"
    sb.setLength(2);

  }
}

public class Main {
  public static void main(String[] args) {
    // Create an empty StringBuffer
    StringBuilder sb = new StringBuilder();
    printDetails(sb);

    // Append "good"
    sb.append("good");
    printDetails(sb);

    // Insert "Hi " in the beginning
    sb.insert(0, "Hi ");
    printDetails(sb);

    // Delete the first o
    sb.deleteCharAt(1);
    printDetails(sb);

    // Append " be with you"
    sb.append(" be with you");
    printDetails(sb);

    // Set the length to 3
    sb.setLength(3);
    printDetails(sb);

    // Reverse the content
    sb.reverse();
    printDetails(sb);
  }

  public static void printDetails(StringBuilder sb) {
    System.out.println("Content: \"" + sb + "\"");
    System.out.println("Length: " + sb.length());
    System.out.println("Capacity: " + sb.capacity());

    // Print an empty line to separate results
    System.out.println();
  }
}

5 (100%) 1 vote
Click Here to Leave a Comment Below 0 comments