[StringBuilder class] Add and reverse methods and convert StringBuilder and String to each other

StringBuilder class

If strings are concatenated, a new String object will be constructed each time they are concatenated, which is time-consuming and wastes memory space, and this operation is unavoidable. We can solve this problem through the StringBuilder class provided by Java. StringBuilder is a variable string class, we can regard it as a container, variable here means that the content in the StringBuilder object is variable

The difference between String and StringBuilder:

  • String: the content is immutable
  • StringBuilder: the content is mutable

1. The construction method of StringBuilder

  • public StringBuilder(): Creates a blank mutable string object without any content

  • public StringBuilder(String str): Create a mutable string object based on the contents of the string

    package com.common.string;
    public class StringDemo08 {<!-- -->
        public static void main(String[] args) {<!-- -->
            StringBuilder sb = new StringBuilder();
            System.out.println("sb:" + sb);
            System.out.println("sb.length():" + sb.length());
            StringBuilder sb2 = new StringBuilder("hello");
            System.out.println("sb2:" + sb2);
            System.out.println("sb2.length():" + sb2.length());
        }
    }
    

2. Add method and reverse method

  • public StringBuilder append (any type): add data and return the data itself

    package com.common.string;
    //add method
    public class StringDemo09 {<!-- -->
        public static void main(String[] args) {<!-- -->
            StringBuilder sb = new StringBuilder();
            /*StringBuilder sb2 = sb.append("hello");
            System.out.println("sb:" + sb);
            System.out.println("sb2:" + sb2);
            System.out.println(sb==sb2);*/
            /*sb.append("hello");
            sb.append("world");
            sb.append("java");
            sb.append(100);*/
            //Chain programming, returning the object itself can use the object to call the method
            sb.append("hello").append("world").append("java").append(100);
            System.out.println("sb:" + sb);
        }
    }
    

    Here, sb and sb2 are tested to see if they are equal, and the added data returns the data itself, so the returned object is still an object. You can directly use the object to call the append() method to simplify the code.

  • public StringBuilder reverse(): returns the reverse character sequence

    package com.common.string;
    //reverse method
    public class StringDemo09 {<!-- -->
        public static void main(String[] args) {<!-- -->
            StringBuilder sb = new StringBuilder();
            sb.append("hello").append("world").append("java").append(100);
            System.out.println("sb:" + sb);
            sb. reverse();
            System.out.println("sb:" + sb);
        }
    }
    

3. Conversion between StringBuilder and String

  • StringBuilder to String

    public String toString(): StringBuilder can be converted to String through toString()

    package com.common.string;
    public class StringDemo10 {<!-- -->
        public static void main(String[] args) {<!-- -->
            StringBuilder sb = new StringBuilder();
            sb.append("hello");
            String s = sb. toString();
            System.out.println(s);
        }
    }
    
  • String to StringBuilder

    public StringBuilder(String s): Convert String to StringBuilder through the construction method

    package com.common.string;
    public class StringDemo10 {<!-- -->
        public static void main(String[] args) {<!-- -->
            String s="hello";
            StringBuilder sb = new StringBuilder(s);
            System.out.println(sb);
        }
    }
    

4. Case: Use StringBuilder’s append method to concatenate strings

Requirement: Define a method to splice the data in the int array into a string according to the specified format and return it, call this method and output the result on the console. For example, the array is int[] arr={1,2,3}, the output after executing the method is: [1,2,3]

Ideas:

1. Define an array of int type, and complete the initialization of the array with static initialization

2. Define a method to splice the data in the int array into a string according to the specified format and return it. The return value type is String, and the parameter list is int[] arr

3. In the method, use StringBuilder to splice according to the requirements, and convert the result into String and return

4. Call the method and use a variable to receive the result

5. Output the result

package com.common.string;
//Use the append method of StringBuilder for splicing
public class StringDemo11 {<!-- -->
    public static void main(String[] args) {<!-- -->
        int[] arr = {<!-- -->1, 2, 3};
        String s = arrayToString(arr);
        System.out.println("s:" + s);
    }
    public static String arrayToString(int[] arr){<!-- -->
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < arr. length; i ++ ) {<!-- -->
            if (i==arr.length-1) {<!-- -->
                sb.append(arr[i]);
            }else{<!-- -->
                sb.append(arr[i]).append(", ");
            }
        }
        sb.append("]");
        String s = sb.toString();//Convert StringBuilder to String type
        return s;
    }
}

5. Case: Use the reverse method in StringBuilder to reverse the string

Requirements: Define a method to implement string inversion, enter a string with the keyboard, and output the result on the console after calling the method. For example: keyboard input abc, output result cba

Ideas:

1. Enter a character string with the keyboard and use Scanner to realize it

2. Define a method to implement string inversion. The return value type is String, and the parameter is String s

3. Use chain programming in the method to call the reverse method first, then convert the string to String and return

4. Call this method and use a variable to receive the result

5. Output the result

package com.common.string;
import java.util.Scanner;
public class StringDemo12 {<!-- -->
    public static void main(String[] args) {<!-- -->
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string: ");
        String line = sc. nextLine();
        String s = reverse(line);
        System.out.println("s:" + s);
    }
    public static String reverse(String s){<!-- -->
        //Convert String to StringBuilder---reverse()----String
        /*StringBuilder sb = new StringBuilder(s);
        sb. reverse();
        String ss = sb. toString();
        return ss;*/
        // use chain programming
        return new StringBuilder(s).reverse().toString();
    }
}