String class (Java language)

preface

We are learning the C language. There is no special type definition for strings, while the Java language has a special type definition for Strings - String. This blog will introduce the explanation of String types in Java in detail.

Create string

Common ways to construct strings

public class TestDemo2 {
    public static void main(String[] args) {
        //Mode 1
        String str = "hello";
        //Mode II
        //Call the constructor to construct the object
        String str2 = new String("hello");
        //Mode III
        char[] chars = {'a', 'b', 'c'};
        String str3 = new String(chars);
        System.out.println(str3);
    }
}

matters needing attention:

  • String literal constants such as "hello" are also of type string.
  • String is also a reference type.

Reference type:

Reference is similar to the pointer in C language, but it opens up a small memory space on the stack to save an address. However, the reference is different from the pointer. The pointer can perform various numerical operations (pointer + 1), but the reference cannot. This is a "less flexible" pointer.
Alternatively, you can think of a reference as a label "pasted" to an object. An object can be labeled with one label or multiple labels. If there is no label on an object, the object will be recycled by the JVM as a garbage object.
Arrays, strings, and custom classes in Java are all reference types.

Therefore, String str = "hello"; The code memory layout is as follows:

Therefore, String str1 = "Hello"; String str2 = str1; The code memory layout is as follows:

So the question is, if you modify str1, will str2 change with it?

str1 = "world";
System.out.println(str2);
// results of enforcement
Hello

In fact, str1 = "world" is not really a "modified" String, but a reference to str1 to a new String object.

Therefore, we know that passing a reference does not necessarily change the corresponding value, but we should start from the bottom to see what the reference does and what it does.

String comparison equality

Reference comparison

If you now have two int variables, you can use = = to judge their equality.

int x = 10 ;
int y = 10 ;
System.out.println(x == y); 
// results of enforcement
true

What about using = = for String objects?
Code 1

String str1 = "Hello";
String str2 = "Hello"; 
System.out.println(str1 == str2); 
// results of enforcement
true 

Code 2

String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2);
// results of enforcement
false

Why does this happen?
For code 1, the memory layout is as follows:

We found that str1 and str2 point to the same object. At this time, string constants such as "Hello" are in the string constant pool.

String constant pool:
String literal constants such as "Hello" also need some memory space to store. One characteristic of such constants is that they do not need to be modified (constants). Therefore, if multiple references in the code need to use "Hello", it is OK to directly refer to the location of the constant pool, instead of storing "Hello" twice in memory. That is, string constant values exist to improve efficiency.

For code 2, the memory layout is as follows:

Through String str1 = new String("Hello"); The String object created in this way is equivalent to opening up additional space on the heap to store the contents of "Hello", that is, there are two copies of "Hello" in memory.

Content comparison

The use of = = in the above String comparison is not to compare the String content, but to compare whether two references point to the same object. So how do you compare the contents of strings? Quite simply, we can compare them through the equals method provided by the String class. for instance:

String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1.equals(str2));
// System.out.println(str2.equals(str1)); //  Or it can be written like this
// results of enforcement
true

So we can compare the contents of the string. Of course, the equals () method has precautions. For example:

String str = new String("Hello");
// Mode 1
System.out.println(str.equals("Hello"));
// Mode II
System.out.println("Hello".equals(str));

In essence, both methods are OK, but there is a problem when using the method. When str is null, the method will throw a null pointer exception. Therefore, we need to pay attention to whether the object using the equals () method will be null.

Understand string immutability

A string is an immutable object. Its content cannot be changed.
The internal implementation of the String class is also based on char [], but the String class does not provide a set method to modify the internal character array.
Let's look at a set of codes:

String str = "hello" ; 
str = str + " world" ; 
str += "!!!" ; 
System.out.println(str); 
// results of enforcement
hello world!!!

Operations such as + = appear to modify the string, but they are not. Memory changes are as follows:
First, open up a space for "hello" and point str to the "hello" object.

Secondly, open up a space for "world", then connect "hello" and "world", then open up a space for "hello world", and finally point to "hello world" by str.

The same is true for the following. Therefore, we know that after + = the str print result changes, but it is not the String object itself that changes, but STR references other objects. Therefore, when programming, we can't have the following similar code, otherwise the efficiency will be very low.

String str = "hello" ; 
for(int x = 0; x < 1000; x++) {
    str += x ; 
}
System.out.println(str);

Characters, bytes and strings

Characters and strings

The string contains a character array. String and char [] can be converted to each other.
Code 1:

public static void main(String[] args) {
        char[] val = {'a', 'b', 'c'};
        String str = new String(val);
        System.out.println(str);
    }

Function: turns all contents in the character array into a string.
Explanation: the String (char val []) constructor converts the contents of the val [] array into a String.
result:

Code 2:

public static void main(String[] args) {
        char[] val = {'a', 'b', 'c','d','e'};
        String str = new String(val,1,3);
        System.out.println(str);
    }

Function: change the contents of some character arrays into strings.
Explanation: the String (char value [], int offset, int count) construction method changes the val [] array from the position with the subscript offset to the subsequent count elements into a String.
result:
Code 3:

public static void main(String[] args) {
        String str = "hello";
        char ch = str.charAt(2);
        System.out.println(ch);
    }

Function: get the characters at the specified index position. The index starts from 0.
Explanation: charAt (int index) method to obtain the character of index subscript in the string.
result:
Code 4:

public static void main(String[] args) {
        String str = "hello";
        char[] chars = str.toCharArray();
        System.out.println(Arrays.toString(chars));
    }

Function: turn the string into a character array and return.
Explanation: the toCharArray () method turns the called string into a character array and returns the array.
result:

Bytes and strings

Code 1:

public static void main(String[] args) {
        byte[] bytes = {97, 98, 99, 100};
        String str = new String(bytes);
        System.out.println(str);
    }

Function: turn byte array into string
Explanation: the String (byte bytes []) construction method turns the bytes [] byte array into the corresponding String.
result:

Code 2:

public static void main(String[] args) {
        byte[] bytes = {97, 98, 99, 100};
        String str = new String(bytes,1,3);
        System.out.println(str);
    }

Function: change the contents of some byte arrays into strings.
Explanation: the String (byte bytes [], int offset, int length) construction method changes the val [] array from the position with the subscript offset to the subsequent count elements into a String.
result:
Code 3:

public static void main(String[] args) {
        String str2 = "abcd";
        byte[] bytes = str2.getBytes();
        System.out.println(Arrays.toString(bytes));
    }

Function: returns a string as a byte array.
Explanation: the getBytes () method turns the called string into a byte array and returns the array.
result:

Summary

  • Byte [] processes strings byte by byte, which is suitable for network transmission and data storage. It is more suitable for binary data operation.
  • char [] handles strings one character by one, which is more suitable for text data operation, especially when Chinese is included.

String common operations

String comparison

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

NO.Method nametypedescribe
1.public boolean equals(Object anObject)ordinaryCase sensitive comparison
2.public boolean equalsIgnoreCase(String anotherString)ordinaryCase insensitive
3.public int compareTo(String anotherString)ordinaryCompare two string size relationships

Code example:

String str1 = "hello" ; 
String str2 = "Hello" ; 
System.out.println(str1.equals(str2)); // false 
System.out.println(str1.equalsIgnoreCase(str2)); // true

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

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

Code example:

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")); //Less than 0

compareTo() is a method that can distinguish between cases. It is a very important method in the String method. The comparison size rules of strings are summarized into 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 unicode value). If there is no winner, compare the following contents in turn.

String lookup

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

NO.Method nametypedescribe
1.public boolean contains(Char Sequence)ordinaryDetermine whether a substring exists
2.public int indexOf(String str)ordinaryFind the position of the specified string from the beginning. If the start index of the return position is found, it returns - 1
3.public int lndexOf(String str,int fromIndex)ordinaryFinds the substring position starting at the specified position
4.public int lastlndexOf(String str)ordinaryFind substring position from back to front
5.public int lastlndexOf(String str,int fromIndex)ordinaryFinds a substring from the specified position from back to front
6.public boolean startsWith(String prefix)ordinaryDetermines whether to start with the specified string
7.public boolean startsWith(String prefix,int toffset)ordinaryJudge whether to start with the specified string from the specified position
6.public boolean endsWith(String suffix)ordinaryDetermines whether to end with the specified string

Code example:
String search, the best use, the most convenient is contains().

String str = "helloworld" ; 
System.out.println(str.contains("world")); // true 

Code example:
Use the indexOf() method to find the location.

String str = "helloworld" ; 
System.out.println(str.indexOf("world")); // 5,w start index
System.out.println(str.indexOf("bit")); // -1. Not found
if (str.indexOf("hello") != -1) { 
 System.out.println("You can find the specified string!"); 
} 

matters needing attention:
When using indexOf(), it should be noted that if the content is repeated, it can only return to the first location of the search. For example:

String str = "helloworld" ; 
System.out.println(str.indexOf("l")); // 2 
System.out.println(str.indexOf("l",5)); // 8 
System.out.println(str.lastIndexOf("l")); // 8 

Code example:
Judge the beginning and end

String str = "**@@helloworld!!" ; 
System.out.println(str.startsWith("**")); // true 
System.out.println(str.startsWith("@@",2)); // ture 
System.out.println(str.endsWith("!!")); // true

String substitution

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

NO.Method nametypedescribe
1.public String replaceAll(String regex,String repalcement)ordinaryReplace all specified contents
2.public String replaceFirst(String regex,String repalcement)ordinaryReplace first content

Code example:
String replacement processing.

String str = "helloworld" ; 
System.out.println(str.replaceAll("l", "_")); //he__owor_d
System.out.println(str.replaceFirst("l", "_")); //he_loworld

matters needing attention:
Since the string is an immutable object, the replacement does not modify the current string, but produces a new string.

String splitting

A complete string can be divided into several substrings according to the specified separator. The available methods are as follows:

NO.Method nametypedescribe
1.public String[] split(String regex)ordinarySplit all strings
2.public String[] split(String regex,int limit)ordinarySplit the string part, and the length of the array is the limit limit

Code example:
Realize the split processing of string.

String str = "hello world hello bit" ; 
String[] result = str.split(" ") ; // Split by space
for(String s: result) { 
 System.out.println(s); 
} 

Code example:
Partial splitting of the string.

String str = "hello world hello bit" ; 
String[] result = str.split(" ",2) ; 
for(String s: result) { 
 System.out.println(s); 
} 

In addition, splitting is a particularly common operation. Some special characters may not be segmented correctly as separators and need to be escaped.
Code example:
Split IP addresses.

String str = "192.168.1.1" ; 
String[] result = str.split("\\.") ; 
for(String s: result) { 
 System.out.println(s); 
} 

Code example:
Split multiple times.

String str = "name=zhangsan&age=18" ; 
String[] result = str.split("&") ; 
for (int i = 0; i < result.length; i++) { 
 String[] temp = result[i].split("=") ; 
 System.out.println(temp[0]+" = "+temp[1]); 
} 

String interception

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

NO.Method nametypedescribe
1.public String substring(int beginIndex)ordinaryTruncates from the specified index to the end
2.public String substring(int beginIndex,int endIndex)ordinaryIntercept part of the content

Code example:
Observe string interception.

String str = "helloworld" ; 
System.out.println(str.substring(5)); //world
System.out.println(str.substring(0, 5)); //hello

matters needing attention:

  1. Index starts at 0.
  2. Pay attention to the writing method of the front closed and back open interval. substring(0, 5) indicates the character containing subscript 0, but not subscript 5.

Other operation methods

NO.Method nametypedescribe
1.public String trim ()ordinaryRemove the left and right spaces in the string and keep the middle space
2.public String toUpperCase()ordinaryString to uppercase
3.public String toLowerCase()ordinaryString to lowercase
4.public String concat(String str)ordinaryIntercept part of the content
5.public int length()ordinaryGet string length
6.public boolean isEmptyordinaryJudge whether it is an empty string, but it is not null, but has a length of 0

Code example:
Observe the use of the trim() method

String str = " hello world " ; 
System.out.println("["+str+"]"); 
System.out.println("["+str.trim()+"]"); 


trim removes white space characters (spaces, newlines, tabs, etc.) at the beginning and end of the string.
Code example:
Case conversion

String str = " hello%$$%@#$% world hahaha "; 
System.out.println(str.toUpperCase()); 
System.out.println(str.toLowerCase());


These two methods convert only letters.
Code example:
String length()

String str = " hello%$$%@#$% world hahaha "; 
System.out.println(str.length());


Note: array length uses array name The length property, and the length() method is used in String.
Well, most of the knowledge about String class is here. If it helps you, don't forget to like it, have comments or ideas. Welcome comments and private letters. Thank you for your support!

Keywords: Java Back-end OOP

Added by Grisu on Wed, 05 Jan 2022 17:30:00 +0200