[JAVASE] Extension of the String class (common methods, StringBuffer, StringBuilder)

Autumn night in September, full of stars with you

Hello, everyone. This is New One. Please pay more attention 🙈🙉🙊. In this blog, Shinichi will introduce the common methods and classes in the String in JAVASE. (The following results are compiled in IDEA.) I hope it can help you while facilitating your review. 😜😜😜🥇🥈🥉

Don't talk nonsense, just enter our article.

I 🥇 Characters, bytes and strings

one point one 🥈 Character and string

In the previous blog about String, we knew that the string contains a character array, and String can be converted to char []

public static void main(String[] args) {
        //1. Convert characters to strings
        char[] val1 = {'a','b','c','d','e'};
        String str1 = new String(val1);
        System.out.println(str1);

        //2. Convert the specified position to a string
        char[] val2 = {'a','b','c','d','e'};
        String str2 = new String(val2,1,3);
        System.out.println(str2);

        //3. Get the characters in the string
        System.out.println("========");
        String str3 = "hello";
        char ch = str3.charAt(2);//Get 2 subscript characters
        System.out.println(ch);
        
        //4. Convert string to character array
        char[] chars = str3.toCharArray();//Convert the string object pointed to by str3 into a character array
        System.out.println(Arrays.toString(chars));
    }

🚀 Small exercise: judge whether the string is composed of numbers

Here we directly use the method isDigit(ch)

public static boolean isNumberChar(String s){
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            /*if (ch < '0' || ch > '9'){
                return false;
            }*/
            if (!Character.isDigit(ch)){
                return false;
            }
        }
        return true;
    }
public static void main(String[] args) {
        String str = "123a567";
        System.out.println(isNumberChar(str));//false
    }

Similar method:
static int compare(char x, char y) -- Compare two char values.
boolean equals(Object obj) -- compares this object with a specified object.
static boolean isLetter(char ch) -- determines whether the specified character is a letter.
static boolean isLetterOrDigit(char ch) -- Determines whether the specified character is a letter or a number.
static boolean isLowerCase(char ch) -- Determines whether the specified character is a lowercase character.
static boolean isUpperCase(char ch) -- determines whether the specified character is an uppercase character.
static boolean isWhitespace(char ch) - determines whether the specified character is a space according to Java.
static String toString(char c) - returns a String object representing the specified char.

one point two 🥈 Characters and Strings

Bytes are often used for data transmission and encoding conversion. String can also be conveniently converted to and from byte []

public static void main(String[] args) throws UnsupportedEncodingException {
        //Byte array to string
        byte[] bytes = {97,98,99,100};
        String str = new String(bytes,1,3);
        System.out.println(str);
        System.out.println("==========");
        
        //String changes to byte array, and the encoding method utf-8 can be changed
        String str2 = "Zhang San";
        byte[] bytes1 = str2.getBytes("utf-8");
        System.out.println(Arrays.toString(bytes1));
    }

Note: The results may vary with the above encoding methods

one point three 🥈 Character array and byte array

Now that we have learned how to convert strings into these two forms, under what circumstances should we use them?

  1. Byte [] is used to process String byte by byte, which is suitable for network transmission and data storage It is more suitable for binary data operation
  2. char [] Right, String is processed one character at a time, which is more suitable for text data operation, especially when it contains Chinese

🚀 Popular science: text data VS binary data

A simple and crude way to distinguish is whether you can read the contents when you open it with Notepad If you can understand, it is text data (such as. java file). If you can't understand, it is binary data (such as. class file)

II 🥇 Common string operations

two point one 🥈 string comparison

The equals() method provided by the String class has been used above. This method itself can make case sensitive equality judgments. In addition to this method, the string class also provides the following comparison operations:

public static void main(String[] args) {
        //Case insensitive comparison - return value is int
        String str1 = "Abcdef";
        String str2 = "abcdef";
        System.out.println(str1.equalsIgnoreCase(str2));//false

        //String comparison, the return value is an integer
        int ret = str1.compareTo(str2);
        System.out.println(ret);//-32 A - a ascii code value subtraction
    }

The compareTo() method is a very important method in the String class. This method returns an integer, and the data will return three types of content according to the size relationship:

1. Equal: return 0
2. Less than: the returned content is less than 0
3. Greater than: the returned content is greater than 0.

🚀 Small exercise

System.out.println("A".compareTo("a")); // -32 
System.out.println("a".compareTo("A")); // 32 
System.out.println("A".compareTo("A")); // 0 
System.out.println("AB".compareTo("AC")); // -1 
System.out.println("Liu".compareTo("Yang"));

compareTo() is a method that can distinguish the size relationship. It is a very important method in the String method. The rule of string comparison size is summarized as three words "dictionary order", which is equivalent to determining whether two strings are in front of or behind a dictionary First, compare the size of the first character (determined according to the value of unicode). If there is no contest, compare the following contents in turn

two point two 🥈 String lookup

Whether the specified content exists can be judged from a complete string. The search method is defined as follows:

public static void main(String[] args) {
        String str1 = "ababcabcd";
        String tmp1 = "abc";

        //Judge whether the field tmp exists in str - similar to strstr in C
        System.out.println(str1.contains(tmp1));
        System.out.println("========");

        //Find the location where the tmp field appears for the first time - the bottom layer is the KMP algorithm
        System.out.println(str1.indexOf(tmp1,3));

        String str2 = "ababcabcd";
        String tmp2 = "abc";

        //Find the mark position forward fromIndex positive order matching
        System.out.println(str2.lastIndexOf(tmp2,4));

        //Judge whether the first field is the given field
        System.out.println(str2.startsWith("c",4));

        //Judge whether the tail field is the given field
        System.out.println(str2.endsWith("cd"));
    }

When using the search method, such as indexof method, if the content is repeated, it can only return the first location of the search

two point three 🥈 String substitution

Replace the existing string data with a specified new string. The available methods are as follows:

public static void main(String[] args) {
        String str = "ababcabcdabcde";

        //Replace the corresponding character with a new character - false replacement to generate a new object
        System.out.println(str.replace("ab", "pp"));

        //Same effect as above
        System.out.println(str.replaceAll("ab","pp"));

        //Replace the first matching field
        System.out.println(str.replaceFirst("ab", "pp"));
    }

Note: since the string is an immutable object, replacement does not modify the current string, but generates a new string

two point four 🥈 String split

A complete string can be divided into several substrings according to the specified delimiter.

public static void main8(String[] args) {
        //Splits a string with a delimiter - the return value is a String array
        String str = "name=zhangsan&age=19";
        String[] strings = str.split("&");
        for (String s:strings
             ) {
            String[] ss  = s.split("=");//Nesting can be separated by different separators
            for (String str1:ss
                 ) {
                System.out.println(str1);
            }
        }
    }

Is there a once and for all method to achieve multi character segmentation by nesting every time? Of course, adding | to separate identifiers in the segmentation function can achieve multi character segmentation.

public static void main(String[] args) {
        // |Processing items as multiple delimiters
        String str = "Java30 12&21#hello";
        String[] strings = str.split(" |&|#");
        for (String s:strings
             ) {
            System.out.println(s);
        }

    }

Let's look at a special set of use cases

public static void main(String[] args) {
        // The. Sign is a special character, which needs to be escaped by /. But at the same time / is also a special character, so / / is required
        String str = "192.168.1.1";
        String[] strings = str.split("\\.",2);//limit refers to the number of divided groups, where there are at most 4 groups
        for (String s:strings
             ) {
            System.out.println(s);
        }
        System.out.println("=============");
        String str2 = "192\\168\\1\\1";
        String[] strings1 = str2.split("\\\\",7);
        for (String s:strings1
             ) {
            System.out.println(s);
        }
    }

be careful:

1. The characters "|", "*", "+" must be added with escape characters and preceded by "\"
2. If it is "", it must be written as " "
3. If there are multiple separators in a string, "|" can be used as a hyphen

Because the HTML built-in syntax defaults to \ as an escape character, some characters need to be preceded by \ to escape

two point five 🥈 String interception

Extract part of a complete string. The available methods are as follows:

public static void main(String[] args) {
        //String interception - New creates a new object
        String str = "abcdefgh";
        System.out.println(str.substring(2,4));//Extract substring cd
        //In java, it is generally left closed and right open
    }

Note: the substring method in java is a left closed right open interval

two point six 🥈 Other operation methods

 public static void main(String[] args) {
        //Remove the space on the left and right sides of the string
        String str1 = "    abc    defg    ";
        System.out.println(str1.trim());
        System.out.println("=============");
        
        //Case conversion - no matter other characters
        String str2 = "abcdefBFRG123";
        System.out.println(str2.toUpperCase());//Conversion from lower case to upper case
        System.out.println(str2.toLowerCase());//Convert capital to small
        
        //String into string constant pool pool operation
        str2.intern();

        //Concatenated string - the concatenated object will not be pooled
        String str = "abcdef";//"" is null, and null means that it does not point to any object
        System.out.println(str.concat("bit"));
        
        //Find string length
        System.out.println(str.length());//method
        int[] array = {1,2,3,4,5};
        System.out.println(array.length);//attribute
        
        //Null judgement
        System.out.println(str.isEmpty());
    }

III 🥇 StringBuffer and StringBuilder

We need to know that the bottom layer of String is the StringBuilder method implemented. Let's review the String method first:

  1. Any String constant is a String object. Once a String constant is declared, it cannot be changed. If the object content is changed, what is changed is the reference point.
  2. Generally speaking, the operation of String is relatively simple, but because of the immutable nature of String, StringBuffer and StringBuilder classes are provided to facilitate String modification.

3.1🥈 StringBuilder

Let's take a look at its implementation:

//StringBuilder
    public static void main(String[] args) {
        /*StringBuilder stringBuilder = new StringBuilder("abcdef");
        System.out.println(stringBuilder);*/
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("abcdef");//Calling the super. Method will not generate a new object
        stringBuilder.append("123456");
        System.out.println(stringBuilder);
    }

Let's take a look at the previous example, string loop splicing

//If string splicing is performed in the loop, try not to use String, just use StringBuilder and StringBuffer
    public static void main3(String[] args) {
         //Generate new objects per cycle - not recommended
        /*String str = "abcdef";
        for (int i = 0; i < 10; i++) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(str).append(i);
            str = stringBuilder.toString();
            //str += i;
        }
        System.out.println(str);*/
       
        //Only string splicing is available for each cycle
        String str = "abcdef";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(str);
        for (int i = 0; i < 10; i++) {
            stringBuilder.append(i);
        }
        str = stringBuilder.toString();.//Call toString method to realize type conversion
        System.out.println(str);
    }

In this way, it is not necessary to create a new object for each splicing, which improves the efficiency

3.2🥈 StringBuffer

The usage of StringBuffer is similar to StringBuilder

public class Test{ 
 public static void main(String[] args) { 
 StringBuffer sb = new StringBuffer(); 
 sb.append("Hello").append("World"); 
 fun(sb); 
 System.out.println(sb); 
 } 
 public static void fun(StringBuffer temp) { 
 temp.append("\n").append("www.bit.com.cn"); 
 } 
}

The biggest difference between String and StringBuffer is that the content of String cannot be modified, while the content of StringBuffer can be modified. Consider using StingBuffer for frequently modifying strings.

Note: String and StringBuffer classes cannot be converted directly. If you want to convert each other, you can use the following principles:
1. String becomes StringBuffer: use the StringBuffer construction method or append() method
2. Change StringBuffer to String: call toString() method.

private static StringBuffer func() {
        String str = "abcdef";
        return new StringBuffer(str);//Call constructor
    }

What is the difference between StringBuffer and StringBuilder? Let's take a look at the bottom

StringBuilder

StringBuffer

It is not difficult to find that the methods implemented by StringBuffer are all synchronized, and this keyword is called lock, which can be used to maintain thread safety. Every time you use and end, you need to lock and unlock, so the time will be slightly longer than that of StringBuilder
In addition, there are methods that String does not have in these two categories:

String inversion

StringBuffer sb = new StringBuffer("helloworld"); 
System.out.println(sb.reverse());

String delete

StringBuffer sb = new StringBuffer("helloworld"); 
System.out.println(sb.delete(5, 10));//Delete data of 5-10

String insertion

StringBuffer sb = new StringBuffer("helloworld"); 
System.out.println(sb.delete(5, 10).insert(0, "Hello"));//After deletion, it is hello, and then insert "Hello" from the beginning, so the output is hello

three point three 🥈 Difference between the three

Interview question: Please explain the difference between String, StringBuffer and StringBuilder:

1. The contents of string cannot be modified. The contents of StringBuffer and StringBuilder can be modified
2. Most functions of StringBuffer and StringBuilder are similar
3. StringBuffer adopts synchronous processing, which belongs to thread safe operation; However, StringBuilder does not adopt synchronous processing, which is a thread unsafe operation
4. Therefore, StringBuilder is usually used for single threads and StringBuffer is used for multi threads

What I want to say to you

Family members, we have learned about the methods of JAVA string operation, but we need to remember that we need to practice day after day 🥳🥳🥳, In the following new session, we will continue to improve the relevant content of JAVA, learn endlessly, and save the world with technology!

Tags: Java C++ Unix

Posted by thehippy on Tue, 13 Sep 2022 22:17:35 +0530