1, String related classes
1. Create string
Properties of String
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** The value is used for character storage. */ private final char value[]; /** Cache the hash code for the string */ private int hash; // Default to 0
Specific JDK API String method attribute resolution: https://www.runoob.com/manual/jdk11api/java.base/java/lang/String.html
- The character content of a String object is stored in a character array. The underlying principle is that String is an array.
- private means that the character array cannot be obtained directly from the outside, and Strinq does not provide qet and set methods of value,
The easiest way to create a string is as follows:
String s1 = "abc";
When a String constant is encountered in the code, the value here is "abc", which will be used by the compiler to create a String object.
Like other objects, you can use keywords and construction methods to create String objects.
Create string with constructor:
String str1=new String("abc");
The String created by String is stored in the public pool, while the String object created by new is on the heap:
String str1 = “abc”; And String str2 = new String("ABC"); What's the difference?
Interview question: string s = new String("abc"); How many objects are created in memory?
Two: one is the new structure in the heap space, and the other is the data in the constant pool corresponding to char []: "abc"
import org.junit.Test; /** * @Description: $ String Use of * @Author: dyq * @Date: $ */ public class StringTest { /* *Conclusion: 1.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. * 2.As long as one of them is a variable, the result is in the heap * 3.If the result of splicing calls the intern() method, the return value is in the constant pool * */ @Test public void test3() { String s1 = "Java"; String s2 ="hello"; String s3 = "Javahello"; String s4= "Java"+"hello"; String s5 =s1+"hello"; String s6="Java"+s2; System.out.println(s3==s4);//true System.out.println(s3==s5);//false System.out.println(s3==s6);//false System.out.println(s5==s6);//false System.out.println(s4==s6);//false String s7 = s6.intern(); //Return the "Javahello" intern() that already exists in the constant value used by s8, and return the canonical representation of the string object. System.out.println(s7==s3);//true } /*String Instantiation method of Method 1: through literal definition Mode 2: through the new + constructor * */ @Test public void test2() { //Through literal definition: at this time, the data javaEE of s1 and s2 is declared in the string constant pool in the method area. String s1 = "javaEE"; String s2 ="javaEE"; //Through the new + constructor: the address values saved in s3 and s4 at this time are the corresponding address values after the data opens up space in the heap space. String s3 = new String("javaEE"); String s4 = new String("javaEE"); System.out.println(s1==s2); //true System.out.println(s3==s4); //false } /*String String, represented by a pair of "" 1,String Declared final and cannot be inherited 2,String Implement Serializable interface: indicates that the string supports serialization. Implement the Comparable interface: indicates that the String can compare the size. 3.String final char[] value is internally defined to store string data 4.String: Represents an immutable character sequence, abbreviated as: immutability Embodiment: 1. When the string is re assigned, the assigned memory area needs to be rewritten, and the original value cannot be used for assignment 2,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 3.When calling the replace() method of string to modify the specified character or string, you also need to re assign the memory area and assign the original value 5.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. 6.Strings with the same content will not be stored in the string constant pool. * */ @Test public void test1(){ String s1 = "abc"; //Definition of literal quantity String s2 = "abc"; s1 = "hello"; System.out.println(s1);//hello System.out.println(s2);//abc System.out.println(s1.equals(s2)); //Compare the address value flash of s1 and s2 System.out.println("*********************"); s1 += "diaolove"; System.out.println(s1); //hellodiaolove System.out.println("*********************"); String s4 = "abc"; String s5 = s4.replace('a', 'b'); // replace is returned from replacing all occurrences resulting in a string oldChar in this string newChar. System.out.println(s5); //bbc int len = s1.length(); System.out.println("The length of the string is" + len); int hash = s1.hashCode(); System.out.println(hash); } }
One interview question:
public class StringTest1 { String str = new String("good"); char[] ch = { 't', 'e', 's', 't' }; public void change(String str, char ch[]) { str = "test ok"; ch[0] = 'b'; } public static void main(String[] args) { StringTest1 ex = new StringTest1(); ex.change(ex.str, ex.ch); System.out.print(ex.str + " and ");//good System.out.println(ex.ch); //best } }
2. String common methods
method | analysis |
---|---|
int length(): | The length of the returned string: return value length |
char charAt(int index): | Returns the character at an index. return value[index] |
boolean isEmpty(): | Judge whether it is an empty string: return value length == 0 |
String toLowerCase(): | Converts all characters in a String to lowercase using the default locale |
String toUpperCase(): | Converts all characters in a String to uppercase using the default locale |
String trim(): | Returns a copy of a string, ignoring leading and trailing whitespace |
boolean equals(Object obj): | Compare whether the contents of the string are the same |
boolean equalsIgnoreCase(String anotherString): | Similar to the equals method, case is ignored |
String concat(String str): | Concatenates the specified string to the end of this string. Equivalent to "+" |
int compareTo(String anotherString): | Compare the size of two strings |
String substring(int beginIndex): | Returns a new string, which is the last substring of the string intercepted from beginIndex. |
String substring(int beginIndex, int endIndex) : | Returns a new string, which is a substring intercepted from beginIndex to endindex (excluding). |
boolean endsWith(String suffix): | Tests whether this string ends with the specified suffix |
boolean startsWith(String prefix): | Tests whether this string starts with the specified prefix |
boolean startsWith(String prefix, int toffset): | Tests whether the substring of this string starting from the specified index starts with the specified prefix |
boolean contains(CharSequence s): | Returns true if and only if this string contains the specified sequence of char values |
int indexOf(String str): | Returns the index of the specified substring at the first occurrence in this string |
int indexOf(String str, int fromIndex): | Returns the index of the specified substring at the first occurrence in this string, starting from the specified index |
int lastIndexOf(String str): | Returns the index of the rightmost occurrence of the specified substring in this string |
int lastIndexOf(String str, int fromIndex): | Returns the index of the last occurrence of the specified substring in this string. Reverse search from the specified index. Note: indexOf and lastIndexOf methods return - 1 if they are not found |
String replace(char oldChar, char newChar): | Returns a new string obtained by replacing all oldchars that appear in this string with newChar. |
String replace(CharSequence target, CharSequence replacement): | Replaces all substrings of this string that match the literal target sequence with the specified literal replacement sequence. |
String replaceAll(String regex, String replacement) : | Replace all substrings of this string that match the given regular expression with the given replacement. |
String replaceFirst(String regex, String replacement) : | Replace this string with the given replacement to match the first substring of the given regular expression. |
boolean matches(String regex): | Tells whether this string matches the given regular expression. |
String[] split(String regex): | Splits the string based on the match of the given regular expression. |
String[] split(String regex, int limit): | Split the string according to the regular expression matching the given string. The maximum number is no more than limit. If it exceeds, all the rest will be put into the last element. |
public class StringTest3 { public static void main(String[] args) { String str = "12hello34world5java7891mysql456"; //Replace the number in the string with,, and remove it if there are at the beginning and end of the result String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", ""); System.out.println(string); //hello,world,java,mysql String str1 = "12345"; //Judge whether all str strings are composed of numbers, i.e. 1-n numbers boolean matches = str1.matches("\\d+"); System.out.println(matches); //true String tel = "0571-4534289"; //Judge whether this is a fixed line telephone in Hangzhou boolean result = tel.matches("0571-\\d{7,8}"); System.out.println(result);//true String str2 = "hello|world|java"; String[] strs = str2.split("\\|"); for (int i = 0; i < strs.length; i++) { System.out.println(strs[i]); /* * hello world java*/ } System.out.println(); String str3 = "hello.world.java"; String[] strs3 = str3.split("\\."); for (int i = 0; i < strs3.length; i++) { System.out.println(strs3[i]); // hello //world //java } } }
Regular expression extension: regular expression
Conversion between String class and other structures
import java.io.UnsupportedEncodingException; import java.util.Arrays; /** * @Description: $ It involves the conversion between String class and others * @Author: dyq * @Date: $ */ public class StringTest4 { public static void main(String[] args) throws UnsupportedEncodingException { // Conversion between String, basic data type and packing type // String -- > basic data type and packing class; Call the static method of wrapper class: parsexxx(str) // Basic data type, wrapper class -- > String: call valueof(xxx) overloaded by String String st1 ="123"; int num = Integer.parseInt(st1); //string to int String st2 = String.valueOf(num); //int to string // Conversion between String and char [] String s = "abc123"; char[] chars = s.toCharArray(); for (int i =0;i<chars.length;i++){ System.out.print(chars[i]+"\t"); } char[] arr = new char[]{'h','e','l','l','o'}; String s1 = new String(arr); System.out.println(s1); // Conversion between String and byte [] // Code: String -- > byte []: call igetBytes() of string // Decoding: byte [-- > String: call the constructor of String // Encoding: String -- > bytes (binary data that can be understood -- > but cannot be understood) // Decoding: the reverse process of encoding, byte -- > string (can't understand binary data) // 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. String s2 ="javaTest Love you"; byte[] bytes = s2.getBytes(); //Use the default character set for conversion System.out.println(Arrays.toString(bytes)); byte[] gbks = s2.getBytes("gbk"); System.out.println(Arrays.toString(gbks)); System.out.println("*********************"); String s3 = new String(bytes); //Decode using the default character set System.out.println(s3); String s4 = new String(gbks); System.out.println(s4); //There is garbled code. Reason: the encoding set and decoding set are inconsistent! String str4 =new String(gbks,"gbk"); System.out.println(str4);//There is no garbled code } }