JavaSE_day11_ Common classes (String class, StringBuffer class, StringBuilder class)

String class

The string class represents a string. All string literals (such as "abc") in a java program are implemented as instances of this class. In other words, all double quoted strings in Java programs are objects of string class. String class in Java Lang package, so you don't need to guide the package when using it!

Characteristics of String class

  • String class: represents a string. All string literals (such as "abc") in Java programs are implemented as instances of this class. String: a string, represented by a pair of "".
  • String is a final class that represents an immutable character sequence. Cannot be inherited.
  • A string is a constant, expressed in double quotation marks. Their values cannot be changed after creation
  • Although the value of String is immutable, String objects created with the = sign are in the constant pool and can be shared.
  • String effect is equivalent to character array (char []), but the underlying principle is byte array (byte [])
  • Assign a value to a string by literal means (different from new). At this time, the string value is declared in the string constant pool. Strings with the same content will not be stored in the string constant pool.
  • . String implements the Serializable interface: indicates that the String supports serialization. The Comparable interface is implemented: it means that the String can compare the size

String: represents an immutable character sequence. Abbreviation: non variability. Reflect the following aspects

  • When the string is re assigned, the assigned memory area needs to be rewritten, and the original value cannot be used for assignment.
  • When connecting an existing string, you also need to assign a value to the memory area again. The original value cannot be used for assignment.
  • When you call the replace() method of String to modify the specified character or String, you also need to reassign the memory area assignment, and the original value cannot be used for assignment.

Common construction methods (String is more than these constructors)

Example:

package com.wrg;
 
 
/*
    String Construction method:
        public String(): Create a blank string object that contains nothing
        public String(char[] chs): Create a string object based on the contents of the character array
        public String(byte[] bys): Create a string object based on the contents of the byte array
        String s = "abc";    Create a string object by direct assignment. The content is abc
        It is recommended to obtain string objects by direct assignment
 */
public class StringDemo {
    public static void main(String[] args) {
        //public String(): Create a blank string object that contains nothing
        String s1 = new String();
        System.out.println("s1:" + s1);//s1:
 
        //public String(char[] chs): Create a string object based on the contents of the character array
        char[] chs = {'a', 'b', 'c'};
        String s2 = new String(chs);
        System.out.println("s2:" + s2);//s2:abc
 
        //public String(byte[] bys): Create a string object based on the contents of the byte array
        byte[] bys = {97, 98, 99};
        String s3 = new String(bys);
        System.out.println("s3:" + s3);//s3:abc
 
        //String s = "abc";    Create a string object by direct assignment. The content is abc
        String s4 = "abc";
        System.out.println("s4:" + s4);//s4:abc
    }
}

The difference between the two methods of creating string objects

  • Create through construction method: for string objects created through new, each new will apply for a memory space. Although the contents are the same, the address values are different.
    String non constant objects are stored in the heap.
  • Create by direct assignment: as long as the character sequence is the same (order and case), no matter how many times it appears in the program code, the JVM will only establish a String object, maintain the String constant in the String pool, and store it in the String constant pool for sharing.

        

Example:

package demo01;

/*
String constant pool: the double quoted string written directly in the program is in the string constant pool.

For basic types, = = is to compare values.
For reference types, = = refers to the comparison of [address value].
 */
public class Demo02StringPool {

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

        char[] charArray = {'a', 'b', 'c'};
        String str3 = new String(charArray);

        System.out.println(str1 == str2); // true
        System.out.println(str1 == str3); // false
        System.out.println(str2 == str3); // false
    }

}

be careful:

  • The splicing results of constants and constants are in the constant pool. And constants with the same content will not exist in the constant pool.
  • String splicing as long as one of them is variable splicing, the result is in the heap
  • If the result of splicing calls the intern() method, the return value is in the constant pool

String usage trap

  • String s1 = "a"; Description: a string with literal "a" is created in the string constant pool.
  •  s1 = s1+"b"; Note: in fact, the original "a" string object has been discarded. Now a string s1+"b" (i.e. "ab") is generated in the heap space. If these operations to change the string content are performed multiple times, a large number of copy string objects will be stored in memory, reducing efficiency. If such operations are put into the loop, it will greatly affect the performance of the program.
  • String s2 = "ab"; Description: directly create a string with literal "ab" in the string constant pool.
  • String s3 = "a" + "b"; Note: S3 refers to the string of "ab" that has been created in the string constant pool.
  • String s4 = s1.intern(); Note: S1 object in heap space will assign the existing "ab" string in constant pool to S4 after calling intern().

Interview question: String s = new String("abc"); How many objects are created in memory?

  • Answer: Two: one is the new structure in the heap space, and the other is the data in the constant pool corresponding to char []: "abc"

String common methods, and other uncommon methods can be learned by querying the API

Method of judging function

  • public boolean equals (Object anObject): compares this string with the specified object.
  • Public Boolean equalsignorecase (string otherstring): compares this string with the specified object, ignoring case.
package demo02;

/*
==Is to compare the address values of objects. If you really need to compare the contents of strings, you can use two methods:

public boolean equals(Object obj): The parameter can be any object. Only if the parameter is a string and the content is the same will it be given true; Otherwise, false is returned.
matters needing attention:
1. Any Object can be received with Object.
2. equals The method has symmetry, that is, a.equals(b) and b.equals(a) have the same effect.
3. If you compare a constant and a variable on both sides, it is recommended to write the constant string in front.
Recommended: "ABC" Equals (STR) not recommended: str.equals("abc")

public boolean equalsIgnoreCase(String str): Ignore case and compare contents.
 */
public class Demo01StringEquals {

    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        char[] charArray = {'H', 'e', 'l', 'l', 'o'};
        String str3 = new String(charArray);

        System.out.println(str1.equals(str2)); // true
        System.out.println(str2.equals(str3)); // true
        System.out.println(str3.equals("Hello")); // true
        System.out.println("Hello".equals(str1)); // true

        String str4 = "hello";
        System.out.println(str1.equals(str4)); // false
        System.out.println("=================");

        String str5 = null;
        System.out.println("abc".equals(str5)); // recommend: false
//        System.out.println(str5.equals("abc")); // Not recommended: error report, null pointer exception NullPointerException
        System.out.println("=================");

        String strA = "Java";
        String strB = "java";
        System.out.println(strA.equals(strB)); // false,Strictly case sensitive
        System.out.println(strA.equalsIgnoreCase(strB)); // true,ignore case

        // Note that only English letters are case sensitive, and others are not case sensitive
        System.out.println("abc I 123".equalsIgnoreCase("abc One 123")); // false
    }

}

Methods of obtaining functions

  • public int length(): returns the length of this string.
  • public String concat (String str): connect the specified string to the end of the string.
  • public char charAt (int index): returns the char value at the specified index.
  • public int indexOf (String str): returns the index of the specified substring that appears in the string for the first time.
package demo02;

/*
String The common methods related to acquisition are:

public int length(): Get the number of characters contained in the string and get the length of the string.
public String concat(String str): Splice the current string and the parameter string into a new string with a return value.
public char charAt(int index): Gets a single character at the specified index position. (start with index 0.)
public int indexOf(String str): Find the index position of the parameter string that appears for the first time in this string. If there is no - 1 value returned.
 */
public class Demo02StringGet {

    public static void main(String[] args) {
        // Gets the length of the string
        int length = "asdasfeutrvauevbueyvb".length();
        System.out.println("The length of the string is:" + length);

        // Splice string
        String str1 = "Hello";
        String str2 = "World";
        String str3 = str1.concat(str2);
        System.out.println(str1); // Hello,wholly intact
        System.out.println(str2); // World,wholly intact
        System.out.println(str3); // HelloWorld,New string
        System.out.println("==============");

        // Gets a single character at the specified index position
        char ch = "Hello".charAt(1);
        System.out.println("The characters at index position 1 are:" + ch);
        System.out.println("==============");

        // Find the first index position of the parameter string in the original string
        // If not, go back-1 value
        String original = "HelloWorldHelloWorld";
        int index = original.indexOf("llo");
        System.out.println("The first index value is:" + index); // 2

        System.out.println("HelloWorld".indexOf("abc")); // -1
    }

}
  • public String substring (int beginIndex): returns a substring, intercepting the string from beginIndex to the end of the string.
  • public String substring (int beginIndex, int endIndex): returns a substring and intercepts the string from beginIndex to endIndex. Including beginIndex and excluding endIndex.  
package demo02;

/*
String interception method:

public String substring(int index): Intercept from the parameter position to the end of the string and return a new string.
public String substring(int begin, int end): Intercept the string from begin to end.
Note: [begin,end), including the left, excluding the right.
 */
public class Demo03Substring {

    public static void main(String[] args) {
        String str1 = "HelloWorld";
        String str2 = str1.substring(5);
        System.out.println(str1); // HelloWorld,wholly intact
        System.out.println(str2); // World,New string
        System.out.println("================");

        String str3 = str1.substring(4, 7);
        System.out.println(str3); // oWo
        System.out.println("================");

        // In the following way, the content of the string remains unchanged
        // There are two strings:"Hello","Java"
        // strA The address value is saved.
        // The original address value is Hello 0 of x666,
        // Later, the address value became Java 0 of x999
        String strA = "Hello";
        System.out.println(strA); // Hello
        strA = "Java";
        System.out.println(strA); // Java
    }

}

Methods of converting functions

  • public char[] toCharArray(): convert this string to a new character array.
  • public byte[] getBytes(): use the default character set of the platform to convert the String encoding into a new byte array.
  • public String replace (CharSequence target, CharSequence replacement): replace the string matching the target with the replacement string.  
package demo02;

/*
String Common methods related to conversion include:

public char[] toCharArray(): Splits the current string into an array of characters as the return value.
public byte[] getBytes(): Gets the byte array at the bottom of the current string.
public String replace(CharSequence oldString, CharSequence newString): 
Replace all existing old strings with new strings and return the new string after replacement.
Note: CharSequence means that string types are acceptable.
 */
public class Demo04StringConvert {

    public static void main(String[] args) {
        // Convert to character array
        char[] chars = "Hello".toCharArray();
        System.out.println(chars[0]); // H
        System.out.println(chars.length); // 5
        System.out.println("==============");

        // Convert to byte array
        byte[] bytes = "abc".getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }
        System.out.println("==============");

        // Content substitution of string
        String str1 = "How do you do?";
        String str2 = str1.replace("o", "*");
        System.out.println(str1); // How do you do?
        System.out.println(str2); // H*w d* y*u d*?
        System.out.println("==============");

        String lang1 = "Will you play! damn you! damn you! damn you!!!";
        String lang2 = lang1.replace("damn you", "****");
        System.out.println(lang2); // Will you play!****!****!****!!!
    }

}

Method of dividing function

  • public String[] split(String regex): split this string into string arrays according to the given regex (rule).  
package demo02;

/*
How to split a string:
public String[] split(String regex): According to the rules of parameters, the string is divided into several parts.

matters needing attention:
split The parameter of the method is actually a "regular expression"
Note today: if you follow the English period "." For segmentation, you must write "\ \." (two backslashes)
 */
public class Demo05StringSplit {

    public static void main(String[] args) {
        String str1 = "aaa,bbb,ccc";
        String[] array1 = str1.split(",");
        for (int i = 0; i < array1.length; i++) {
            System.out.println(array1[i]);
        }
        System.out.println("===============");

        String str2 = "aaa bbb ccc";
        String[] array2 = str2.split(" ");
        for (int i = 0; i < array2.length; i++) {
            System.out.println(array2[i]);
        }
        System.out.println("===============");

        String str3 = "XXX.YYY.ZZZ";
        String[] array3 = str3.split("\\.");
        System.out.println(array3.length); // 0
        for (int i = 0; i < array3.length; i++) {
            System.out.println(array3[i]);
        }
    }

}

String and other data type conversion

Character array ----- > string

  • Constructor of String class: String(char []) and String(char [], int offset, int length) create String objects with all characters and some characters in the character array respectively.

String ----- -- > character array

  • public char[] toCharArray(): a method to store all characters in a string in a character array.
  • public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): provides a method to store strings within the specified index range into an array.

Byte array ----- > string

  • String(byte []): construct a new string by decoding the specified string array using the default character set of the platform.
  • String(byte [], int offset, int length): use a part of the specified byte array, that is, take length bytes from the starting offset of the array to construct a string object.

String ----- -- > byte array

  • public byte[] getBytes(): encode this String as a byte sequence using the default character set of the platform, and store the result in a new String array.
  • public byte[] getBytes(String charsetName): encodes this String into a String string String sequence using the specified character set, and stores the result in a new String string String array.
package demo01;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * It involves the conversion between String class and other structures
 *
 * @author shkstart
 * @create 2019 2:39 PM
 */
public class StringTest1 {


    /*
    String Conversion between and byte []
    Code: String -- > byte []: call getBytes() of string
    Decoding: byte [] -- > String: call the constructor of String

    Encoding: String -- > bytes (binary data that can be understood -- > but cannot be understood)
    Decoding process of binary encoded data (not understandable)

    Note: when decoding, it is required that the character set used for decoding must be consistent with the character set used for encoding, otherwise garbled code will appear.
     */
    @Test
    public void test3() throws UnsupportedEncodingException {
        String str1 = "abc123 China";
        byte[] bytes = str1.getBytes();//Use the default character set for encoding.
        System.out.println(Arrays.toString(bytes));

        byte[] gbks = str1.getBytes("gbk");//use gbk Encode the character set.
        System.out.println(Arrays.toString(gbks));

        System.out.println("******************");

        String str2 = new String(bytes);//Decode using the default character set.
        System.out.println(str2);

        String str3 = new String(gbks);
        System.out.println(str3);//Garbled code appears. Cause: the encoding set and decoding set are inconsistent!


        String str4 = new String(gbks, "gbk");
        System.out.println(str4);//There is no garbled code. Reason: the encoding set and decoding set are consistent!


    }

    /*
    String Conversion between and char []

    String --> char[]:Call toCharArray() of String
    char[] --> String:Call the constructor of String
     */
    @Test
    public void test2(){
        String str1 = "abc123";  //Title: a21cb3

        char[] charArray = str1.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            System.out.println(charArray[i]);
        }

        char[] arr = new char[]{'h','e','l','l','o'};
        String str2 = new String(arr);
        System.out.println(str2);
    }

    /*
    review:
    String Conversion with basic data types and wrapper classes.

    String --> Basic data type and wrapper class: call the static method of wrapper class: parseXxx(str)
    Basic data type, wrapper class -- > String: call valueOf(xxx) overloaded by String

     */
    @Test
    public void test1(){
        String str1 = "123";
//        int num = (int)str1;//FALSE
        int num = Integer.parseInt(str1);

        String str2 = String.valueOf(num);//"123"
        String str3 = num + "";

        System.out.println(str1 == str3);
    }

}

Enter a string on the keyboard and count the number of occurrences of various characters. The types are: capital letters, lowercase letters, numbers and others

package demo02;

import java.util.Scanner;

/*
Idea:
1. Since keyboard input is used, it must be Scanner
2. If the keyboard input is a string, then: String str = sc.next();
3. Define four variables to represent the occurrence times of the four characters.
4. You need to check the string word by word. String -- > char [], the method is toCharArray()
5. Traverse the char [] character array, judge the type of the current character, and use four variables for + + action.
6. Print out four variables, representing the occurrence times of four characters respectively.
 */
public class Demo07StringCount {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string:");
        String input = sc.next(); // Gets a string entered by the keyboard

        int countUpper = 0; // capital
        int countLower = 0; // Lowercase letters
        int countNumber = 0; // number
        int countOther = 0; // Other characters

        char[] charArray = input.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            char ch = charArray[i]; // Current single character
            if ('A' <= ch && ch <= 'Z') {
                countUpper++;
            } else if ('a' <= ch && ch <= 'z') {
                countLower++;
            } else if ('0' <= ch && ch <= '9') {
                countNumber++;
            } else {
                countOther++;
            }
        }

        System.out.println("Capital letters are:" + countUpper);
        System.out.println("Lowercase letters are:" + countLower);
        System.out.println("The numbers are:" + countNumber);
        System.out.println("Other characters are:" + countOther);
    }

}

StringBuffer class

Overview: Java Lang. StringBuffer represents variable character sequence, jdk1 0, the String content can be added or deleted, and no new object will be generated at this time. Many methods are the same as String. When passed as a parameter, the value can be changed inside the method. The methods of StringBuffer and StringBuilder are basically the same. The only difference is efficiency.

Differences among StringBuilder class, String class and StringBuffer

Common construction methods

The StringBuffer class is different from String, and its object must be generated using a constructor. There are three constructors:

  • StringBuffer(): a string buffer with an initial capacity of 16
  • StringBuffer(int size): construct a string buffer with a specified capacity
  • StringBuffer(String str): initializes the content to the specified string content

common method

  • StringBuffer append(xxx): provides many append() methods for string splicing
  • StringBuffer delete(int start,int end): deletes the contents of the specified location
  • StringBuffer replace(int start, int end, String str): replace the [start,end) position with str
  • StringBuffer insert(int offset, xxx): insert xxx at the specified position
  • StringBuffer reverse(): reverses the current character sequence

Code demonstration

public class StringBuilderDemo {
    public static void main(String[] args) {
        //create object
        StringBuilder sb = new StringBuilder();
        //public StringBuilder append(Any type): Add data and return the object itself
        //Chain programming
        sb.append("hello").append("world").append("java").append(100);
        System.out.println("sb:" + sb);
        //public StringBuilder reverse(): Returns the opposite sequence of characters
        sb.reverse();
        System.out.println("sb:" + sb);
    }
}

Conversion between StringBuilder and String

  • Converting StringBuilder to String: public String toString(): you can convert String builder to String through toString()
  • Convert String to StringBuilder: public StringBuilder(String s): you can convert String to StringBuilder through construction method

 

Tags: JavaSE

Posted by phprocky on Tue, 24 May 2022 18:45:03 +0300