Java Basic Tutorial - String Class

Keywords: Delphi Java JDK ascii Programming

String class

All string literals (such as "abc") in Java programs are examples of String
Strings are constants (String objects are immutable, so they can be shared)
The essence of a string is an array of characters: private final char value [];

Common ways to create strings

public class CreateString {
    public static void main(String[] args) {
        // Direct definition of strings
        String str1 = "Tiger and Lion";
        // new string
        String str2 = new String("Java");
        // Character Array String
        char[] arrChar = { 'A', 'n', 'd', 'y' };
        String str3 = new String(arrChar);
        // Byte Array String
        byte[] arrByte = { 97, 98 };
        String str4 = new String(arrByte);
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
    }
}

String comparison

public class string comparison {
    public static void main(String[] args) {
        String s1 = "Kuimu Wolf";
        String s2 = "Kuimu Wolf";
        String s3 = new String("Kuimu Wolf");
        System.out.println(s1 == s2);
        System.out.println(s1 == s3);
    }
}

Analysis:

Strings created with literal values are stored in a constant pool. String objects of the same content point to the same string object.
Strings in the constant pool are either created or used directly.

String Constant Pool:
It's equivalent to caching, which makes the program run faster.
Previously, in the method area, after JDK 1.7, moved to heap memory area.

new String() creates string objects at runtime, not in the constant pool, so s3 and s1 and s2 are not the same objects.

With regard to the use of=== for comparative judgement:

| Basic types, numerical comparison (as long as the values are equal, the types can be different)
| - Reference type, address comparison (true only if it points to the same object)

public class Basic Types of Double Signs {
    public static void main(String[] args) {
        int a = 97;
        double b = 97.0;
        char c = 'a';
        System.out.println(a == b);// true
        System.out.println(c == b);// true
    }
}
equals method

The String class provides equals methods for string comparison.
Look at the source code for this method:

When addresses are equal, they are directly equal. When the addresses are not equal, the lengths are directly determined to be unequal; when the lengths are equal, one character is compared.

    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

Application:

public class string comparison {
    public static void main(String[] args) {
        String s1 = "Kuimu Wolf";
        String s2 = "Kuimu Wolf";
        String s3 = new String("Kuimu Wolf");
        System.out.println(s1.equals(s3));
        System.out.println(s3.equals("Kuimu Wolf"));// No recommendation, possible null pointer exception
        System.out.println("Kuimu Wolf".equals(s3));// Recommend
    }
}

It is recommended to call equals method with string literal value, even with "...". equals(...), because the string literal value in quotation marks must not be null, and the calling method will not have null pointer exception.
But many times, it's impossible to determine whether it's null (for example, the object calling the equals method is a parameter passed in from somewhere else).
If you are not sure that the object calling equals is not null, you need to make null judgment before calling.

if (s3 != null) {
    boolean equals = s3.equals(s2);
    System.out.println(equals);
}

Or use the equals method provided by the Objects class to compare. Objects classes are provided from JAVA 1.7 to prevent null pointer exceptions.

        String s1 = "Kuimu Wolf";
        String s2 = "Kuimu Wolf";
        String s3 = new String("Kuimu Wolf");
        boolean equals = Objects.equals(s2, s3);
        System.out.println(equals);// true
More string comparison methods:
boolean equalsIgnoreCase(String anotherString) Determine whether the string anotherString is equal to the current string, ignoring case and case
int compareTo(String anotherString) Comparing string anoterString with current string size according to ASCII code is similar to strcmp function in C language.
boolean startsWith(String prefix) Determine whether the current string begins with prefix
boolean endsWith(String suffix) Determine whether the current string is suffixed with the string suffix
public class Test string comparison {
    public static void main(String[] args) {
        String str1 = "ABC";
        System.out.println(str1.equalsIgnoreCase("abc"));// Equals IgnoreCase is more important
        System.out.println(str1.compareTo("ABB"));// 1
        System.out.println(str1.compareTo("ABC"));// 0
        System.out.println(str1.compareTo("ABD"));// -1
        System.out.println(str1.startsWith("AB"));// T
        System.out.println(str1.endsWith("C"));// T
    }
}

String variable reassignment, in fact, the original string content is unchanged, but the address referenced in the variable has changed.

Therefore, the string stitching, substitution and space removal operations mentioned later will result in new strings.

public class String variable content unchanged {
    // Description: System.identityHashCode(Onject): Different objects, this result will be different
    public static void main(String[] args) {
        String s1 = "Yellow-robed Monster";
        System.out.println(System.identityHashCode(s1));
        s1 = "Kuimu Wolf";// s1 holds the address value. The previous string object has not changed, but the address of s1 has changed.
        System.out.println(System.identityHashCode(s1));
        String s2 = "Yellow-robed Monster";
        System.out.println(System.identityHashCode(s2));
    }
}

String extraction

char charAt(int index) Extracts a single character from a specified position specified by an index (index value)
String substring(int index) Extract a partial string starting at the location specified by index
String substring(int begin, int end) Extract partial strings between begin and end positions
String concat(String str) Connect two strings and create a new string object containing the calling string
String replace (char oldChar, char newChar) Replace all characters specified by oldChar in the string with those specified by newChar
replaceAll(String regex, String replacement) Replace all strings matching regex in the string with the characters specified by replacement
String trim() By removing the space before and after the string, you get a new string.
public class Test Extract strings {
    public static void main(String[] args) {
        String str1 = "<In Journey to the West, why do Tathagata preach sutras?";
        String str2 = new String("Pudu all living beings, one can not let go!");
        System.out.println("------------lookup--------------");
        int _index = 2;
        char _c = str1.charAt(_index);
        System.out.println("charAt " + _index + ":" + _c);
        System.out.println("------------substring--------------");
        String _subStr = str1.substring(_index);
        System.out.println("substring(" + _index + "):" + _subStr);
        int _begin = 2, _end = 9;
        _subStr = str1.substring(_begin, _end);
        System.out.println("substring(" + _begin + "," + _end + "):" + _subStr);
        System.out.println("------------Splicing--------------");
        System.out.println("concat:" + str1.concat(str2));
        System.out.println("String + String:" + str1 + str2);
        System.out.println("------------replace--------------");
        char oldC = 'west', newC = 'east';
        String _newString = str1.replace(oldC, newC);
        System.out.println("replace(" + oldC + "," + newC + ") :" + _newString);
        String _tar = "remember", _repl = "Shi Erzhuan";
        _newString = str1.replace(_tar, _repl);
        System.out.println("replace(" + _tar + "," + _repl + "):" + _newString);
        _newString = "tel:10086".replaceAll("\\d", "*");
        System.out.println("replaceAll(number→*):" + _newString);
        System.out.println("------------Despace--------------");
        String s = " A B C  ".trim();
        System.out.println("trim:[" + s + "]");
    }
}

Converting strings to other formats

byte[] getBytes() Converts a string to a byte array (that is, the most primitive binary form of a string stored in memory)
char[] toCharArray() Converting a string to an array of characters, similar to the form of string preservation in C
public class Test String Conversion {
    public static void main(String[] args) {
        byte[] b;
        b = "Hello Java".getBytes();
        for (int i = 0; i < b.length; i++) {
            System.out.print("[" + b[i] + " " + (char) b[i] + "]");
        }
        System.out.println("-------------------------");
        char[] c;
        c = "Hello Java".toCharArray();
        for (int i = 0; i < c.length; i++) {
            System.out.print(" " + c[i]);
        }
    }
}

The string is converted to an array of strings (. split(...)):

public class StringSplit {
    public static void main(String[] args) {
        String[] sArr = "01,Cephalosporin,Hubaoyi,Song Jiang".split(",");
        for (String s : sArr) {
            System.out.println(s);
        }
    }
}

StringBuiler and StringBuffer

StringBuiler/StringBuffer represents a variable character sequence (that is, a variable string)

Connecting strings with the "+operator" will create new strings. When strings are frequently modified, StringBuilerh or StringBuffer classes are generally used to improve efficiency.

public class StringB {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("various");
        sb.append("Arrowroot");
        sb.append("hole");
        sb.append("bright");
        System.out.println(sb.toString());
    }
}

Resolution: String's value is final, so the storage array at the bottom of the string is unchanged, creating objects every append.

private final char value[];

StringBuilder is not final

char[] value;// Definition in the abstract class AbstractStringBuilder
StringBuilder class
Construction method () Constructor: Create an empty StringBuffer object
Construction Method (String str) Constructor: Create StringBuffer objects based on the contents of the string str
append(x) Adding content: unlimited type
insert(int index, x) Insert: Insert x into an index location where x can be any type of data
delete(int start, int end) Delete: Start from the start position until the index position specified by the end
deleteCharAt(int index) Delete the character at the index specified by: index
setCharAt(int index, char ch) Replacement: Replace characters at the location specified by index with a new value specified by ch
replace(int start, int end, String str) Replacement: Start at the location specified by start until the end of the location specified by end
reverse() Character sequence inversion
length() length
String toString() Convert to string type
public class TestStringBuXXX {
    static void m The most commonly used method() {
        StringBuilder sb = new StringBuilder();
        // [.length()]
        System.out.println("length():" + sb.length());
        // [.append()]
        sb.append("ABC,");
        sb.append(true);
        // [.toString()]
        System.out.println("append():" + sb.toString());
        // Chain programming: The append method returns itself and can continue append
        sb.append("Green lion").append("White elephant").append("roc");
        System.out.println(sb.toString());
        // [transpose:. reverse()]
        sb.reverse();
        System.out.println("Transposition:" + sb.toString());
        // [Clean up:. setLength(0)]
        sb.setLength(0);
        System.out.println("empty:" + sb.toString());
    }
    static void m Other common methods() {
        StringBuffer sb = new StringBuffer("ABCDEFGHI");
        System.out.println("---insert---");
        sb.insert(2, "123");
        System.out.println("|--insert():" + sb);
        System.out.println("---delete---");
        sb.delete(2, 2 + 3);
        System.out.println("|--delete():" + sb);
        sb.deleteCharAt(2);
        System.out.println("|--deleteCharAt():" + sb);
        System.out.println("---replace---");
        sb.setCharAt(2, '*');
        System.out.println("|--setCharAt():" + sb);
        sb.replace(1, 1 + 4, "#@");
        System.out.println("|--replace():" + sb);
    }
    public static void main(String[] args) {
        m The most commonly used method();
        m Other common methods();
    }
}

* StringBuffer and StringBuilder are used in the same way. StringBuilder is suitable for single-threaded environments and has high efficiency.

* StringBuffer is a new addition to JDK 1.5.

Example: Palindrome

Write a way to judge whether a sentence is a palindrome (English is case-insensitive).
For example: Able was I ere I saw Elba
For example, if it is true, it is true.

public class Palindrome {
    public static void main(String[] args) {
        String s = "Able was I ere I saw Elba";
        check(s);
        s = "False is true and false.";
        check(s);
    }
    static void check(String s) {
        String sLower = s.toLowerCase();
        System.out.println(sLower);
        StringBuffer s2 = new StringBuffer(sLower);
        s2.reverse();
        System.out.println(s2);
        if (sLower.equals(s2.toString())) {
            System.out.println("It's palindrome");
        } else {
            System.out.println("Not palindrome");
        }
    }
}

* Extension. MessageFormat

java.text.MessageFormat

import java.text.MessageFormat;
import java.util.Date;

public class TestMessageFormat {
    public static void main(String[] args) {
        String template = "Full name:{0},Age:{1},Time:{2}";
        String s = MessageFormat.format(template, "Chen Xuanzang", 28, new Date());
        System.out.println(s);
        System.out.printf("Full name:%s,Age:%d,Time:%s", "Chen Xuanzang", 28, new Date());
    }
}

Posted by alexdoug on Fri, 12 Jul 2019 11:14:58 -0700