Summary of Java knowledge points [4] String

1. Creation of String

1)String str1="hello"; 

2)String str2=new String("hello"); 

3) Construct a string by char[] or byte[]

char[] arr={'h','e','l','l','o'};
String str3=new String(arr);

Among them, the first method is the most commonly used. In fact, there are many creation methods, not only the above three, please check it when you need it~

2. String comparison is equal

1) == compares the identity of the object (compare whether the addresses saved in the two references are the same/compare whether the two references point to the same object)

Example ①

String str1="hello";
String str2="hello";
System.out.println(str1==str2);

result

analysis:

Like "hello" The string literal constant is the presence of a string constant pool in time with direct reference to the location of the constant pool hello on the line, you can save a copy, no need stored twice in memory. So our two references above str1 and str2 actually point to the same hello object, so == after comparing the identities of the objects, the result is true.

Example ②

String str1=new String("hello");
String str2=new String("hello");
System.out.println(str1==str2);

result

analysis:

In the above code, we use the new keyword to create two objects, let str1 and str2 point to these two objects respectively. Since it points to different objects, the result of == comparison is false.

It can also be seen that the direct assignment method to create a string is more efficient. When a string with the same content is quoted multiple times, there is no need to engage in so many objects. One string constant pool is enough.

2) The equals method compares the contents of two strings (only for String type)

String str1=new String("hello");
String str2=new String("hello");
System.out.println(str1.equals(str2));//也可写成str2.equals(str1)

The result is true

System.out.println(str1.equals("hello"));
System.out.println("hello".equals(str1));

Of the above two methods, it is recommended to write the second one. Since str1 is a variable of reference type in the first type, the null reference type cannot be dereferenced. Once str1 is a null reference, an exception will be thrown, and the literal constant will not involve this problem~

3. String constant pool

The pool is an important way of thinking. It creates and saves some frequently used objects in advance, so that they can be used at any time, reducing overhead and improving efficiency.

4. Add the contents of the String object to the string constant pool

Use the intern method

Example:

String str1=new String("hello");
System.out.println("hello"==str1);
String str2=new String("hello").intern();
System.out.println("hello"==str2);

result

analysis:

The constant pool is a memory area divided by the JVM. When the JVM runs, it will specialize in an area called the constant pool (also a part of the heap)

In the above code, when the intern() method is called, the contents of the current string will be searched in the string constant pool to see if it exists in the constant pool. If it exists, the address in the pool will be directly returned; If it does not exist, the content of the current string is added to the constant pool, and the address in the pool is returned.

5. Strings are immutable

The content of the char[] value array held in the String array cannot be changed outside the class, which is a manifestation of encapsulation.

advantage:

1) Convenient to put in the pool

2) The hashCode is also not changeable

3) Thread safety is more guaranteed

6. Use reflection mechanism to modify the content of String

As we said above, a string is an immutable object. If we want to change it, just create a new one.

But there is also a special way to modify the content of String, using reflection mechanism. If you knock on my door, I will definitely not open the door, but if it is the police uncle to handle the case, it is legal to break in~

Reflection is an important feature of object-oriented programming.

Reflection and encapsulation are the opposite:

1) Using reflection may often break the package

2) The reflected code is more complicated and error-prone

3) Reflection sacrifices some checking and verification mechanisms of the compiler itself, and requires programmers to manually ensure the correctness of the code.

7. The mutual conversion between character arrays, byte arrays, and strings

Character array/byte array—>String: The third way to create a string above~, toString() method

String— >Character array: toCharArray

String— >Byte array: getBytes

Example:

//字符数组/字节数组—>字符串
    char[] arr1={'a','b','c'};
    String str1=new String(arr1);
//字符串—>字符数组
    String str2="hello";
    char[] arr2=str2.toCharArray();
//字符串—>字节数组
    String str3="hello";
    byte[] arr3=str3.getBytes();

 

8. String comparison size

1) Case is not ignored, and the result is a number : use the compareTo() method

String a="Hello";
String b="hello";
System.out.println(a.compareTo(b));

result

analysis:

According to unicode comparison, the first character is compared first, and if the first character is equal, the next one is continued; a>b returns a number greater than 0; a<0 returns a number less than 0; a==b returns 0

In the above code, the uppercase H is obviously smaller than the lowercase h (as can be seen in the ASCLL code table), so the number returned is <0

2) Ignore case, the result is a number : use compareToIgnoreCase() method

String a="Hello";
String b="hello";
System.out.println(a.compareToIgnoreCase(b));

result

analysis:

Same as the above rule, except that case is ignored, that is, uppercase H and lowercase h are the same size, and the two strings are the same size, so 0 is returned.

3) Ignore case, the result is Boolean type : use equalsIgnoreCase() method

String a="Hello";
String b="hello";
System.out.println(a.equalsIgnoreCase(b));

result

analysis:

After ignoring case, each character in the two strings is the same size, so return true

9. String contains

Use contains() method , the result is boolean type

String a="Hello world java";
String b="java";
System.out.println(a.contains(b));

result

note:

Take the above code as an example, a.contains(b) looks at whether the a string contains the b string . If it cannot be written inverted, the result will be different.

10. Subscript starting position of substring

1) From the look left to right substring, if found return index of the first occurrence location: Use the indexOf () method

String a="Hello java java";
String b="java";
System.out.println(a.indexOf(b));

result

2) from right to left to find substring, if the index to find the first occurrence of the return position: Use lastIndexOf () method

String a="Hello java java";
String b="java";
System.out.println(a.lastIndexOf(b));

result

11. Determine that the string starts/ends with XXX

1) Judgment starts with XXX : use the startWith() method, and the return result is boolean type

Usage: In network programming, determine the protocol type of a link

String a="https://www.baidu.com";
String b="https://";
System.out.println(a.startsWith(b));

result

2) Judge to end with XXX : use endsWith() method, return result is boolean type

Usage: determine the type of a file

String a="a.java";
String b=".java";
System.out.println(a.endsWith(b));

result

12. String replacement

1) replace the string appearing in all sub-string: using the replaceAll () method

String a="Hello world world";
String b="world";
System.out.println(a.replaceAll(b,"java"));

result

2) Replace the first occurrence of the substring in the string: use the replaceFrist() method

String a="Hello world world";
String b="world";
System.out.println(a.replaceFirst(b,"java"));

result

13. String split

Use split() method

Example ①Split by space

String a="Hello world java";
String[] result=a.split(" "); //分割符为空格
for(String x:result){
    System.out.println(x);
}

result

Example ② Press. to split

String a="Hello.world.java";
String[] result=a.split("\\.");
for(String x:result){
    System.out.println(x);
}

result

analysis:

It can be found that there are two more backslashes \\ in front of the division according to.

Regex stands for regular expressions. There are many special symbols in regular expressions. "." is one of them. To solve this problem, you need to use the escape characters in "regular expressions", that is, regular expressions. "." is treated as a special symbol, and "\." is treated as. Itself. Next, the string in Java regards \ as the escape character of Java again. In order to represent an original \, it needs to be escaped again. Eventually "\\."

In general, a.split("\\."); involves two escapes, one is the escape in Java, and the other is the escape in regular expressions

14. String interception

Use the substring() method

1) Intercept an interval [begin, end), before closing and then opening

String a="Hello world java";
System.out.println(a.substring(6,11));

result

2) Start intercepting from a certain position (including this position)

String a="Hello world java";
System.out.println(a.substring(6));

result

15. Other

1) Remove left and right blank characters: use trim() method

String a="    Hello world  ";
System.out.println("["+a.trim()+"]");

result

Note: White space includes: space, line feed, carriage return, tab, page turning, vertical tab...

2)

  • toUpperCase() //turn lowercase letters to uppercase
  • toLowerCase() //Uppercase letters to lowercase
  • intern() //String into the pool
  • concat() //string splicing, equivalent to "+"
  • isEmpty() //Determine whether it is a blank string

16.StringBuffer和StringBuilder

StringBuffer, StringBuilder and String are different classes. As mentioned above, the content of the variable created by the String type is immutable unless a special method (reflection mechanism) is used. However, in order to facilitate the modification of the string, the StringBuffer class and the StringBuilder class are introduced, which means that the contents pointed to by the variables created by these two classes can be modified.

① Splicing at the end of the string: use the append() method

 

StringBuffer str=new StringBuffer("hello");
for(int i=0;i<5;i++){
    str.append(i);
}
System.out.println(str);

result

Analysis: The append() method is to directly splice the parameters to the end of the original memory. If the spliced ​​content is too much and exceeds the range of the memory, str will automatically expand.

②String reversal: use the reverse() method

StringBuffer str=new StringBuffer("hello");
System.out.println(str.reverse());

result

③Delete the substring in the specified subscript range: use the delete() method, the range is [begin,end) before closing and then opening

StringBuffer str=new StringBuffer("Hello,java,world");
System.out.println(str.delete(6,11));

result

④ Insert data to the specified location: use the insert() method

StringBuffer str=new StringBuffer("Hello rld");
System.out.println(str.insert(6,"wo"));

result

To summarize StringBuider and StringBuffer:

The related operations of the two classes are not much different. The above is an example of the operation of the StringBuffer class.

Core difference: StringBuilder thread is not safe, StringBuffer thread safe

Guess you like

Origin blog.csdn.net/weixin_43939602/article/details/112851312