Common methods of String class in Java
The following introduces several common methods for strings.
Introducing the String class
In Java,String
class is a class that represents a string and has the following properties:
-
Immutability:
String
Objects are immutable once created, i.e. their values cannot be changed after creation. any pairString
Modification operations on an object actually create a newString
object. -
String pool: The string pool in Java is a special memory area used to store string constants. When a string is created, it first checks whether a string with the same value already exists in the string constant pool. If it exists, it returns the string reference in the pool without creating a new object.
-
Compare:String can be passed
equals()
method to compare whether their contents are the same. In Java, useequals()
Compare string contents instead using==
To compare object references for equality. -
Security through immutability: Since strings are immutable, they can be safely passed as arguments to methods to avoid being accidentally modified.
-
performance: Since strings are immutable, they can be cached and reused, and can be used during string concatenation.
StringBuilder
orStringBuffer
class to improve performance. -
String operation methods:
String
The class provides many methods for operating on strings, such aslength()
、charAt(index)
、substring()
Etc., these methods can help developers process strings conveniently.
In general,String
Classes play an important role in Java and are one of the classes frequently used in development. Its immutability and string pooling features make string processing safer and more efficient.
1. Splicing:
In Java,String
classconcat()
method and+
Operators are used to concatenate strings. Both methods concatenate two strings to form a new string, but there are some minor differences:
-
concat()
method:concat()
The method isString
Instance method of the class that concatenates the specified string to the end of the string on which the method is called. It returns a new string object, the original string is unaffected. For example:
String str1 = "Hello";
String str2 = "World";
String result = (str2); // The result is "HelloWorld"
-
+
Operator:+
The operator can also be used for string concatenation, which can connect two strings (it can also connect strings and other data types, and perform type conversion). This method is more common in Java. For example:
String str1 = "Hello";
String str2 = "World";
String result = str1 + str2; // The result is "HelloWorld"
The main difference is in the syntax form, using operators+
when, in fact, it is through theString
classconcat()
Method is implicitly called to implement string concatenation.
In actual development,+
The operator is more commonly used because it is more intuitive and can be mixed with other data types, such as:
String name = "Alice";
int age = 30;
String message = "My name is " + name + " and I am " + age + " years old.";
In the above code,+
The operator not only concatenates multiple strings, but also converts integer types into strings to form complete output information.
In general, whether usingconcat()
The method is still+
The ultimate purpose of the operator is to concatenate multiple strings into a new string.
2. Compare strings for equality:
When we want to compare whether two strings are the same, we need to pay special attention to whether we actually want to compare whether the contents of the strings are the same. Must useequals()
method but cannot be used==
。
Let's look at the following example:
// String
public class Main {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
(s1 == s2);
((s2));
}
}
On the surface, two strings using==
andequals()
Comparison istrue
, but in fact it is just that the Java compiler will automatically treat all the same strings as an object and put them into the constant pool during compilation. Naturallys1
ands2
The references are the same.
So, this kind of==
compare returntrue
Pure coincidence. Change the way of writing,==
The comparison will fail:
// String
public class Main {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "HELLO".toLowerCase();
(s1 == s2);
((s2));
}
}
Conclusion: To compare two strings, you must always useequals()
method.
3. Compare the size of strings:
In Java,String
class providescompareTo()
method andcompareToIgnoreCase()
Method used to compare the size relationship between strings. Both methods return integer values that represent the lexicographic relationship between two strings. Here is their introduction:
-
compareTo()
method:-
compareTo()
The method is used to compare two strings in lexicographic order and return an integer value. Different values are returned depending on the comparison results:- If the calling string is less than the argument string, a negative integer is returned.
- If the calling string is greater than the argument string, a positive integer is returned.
- If the two strings are equal, 0 is returned.
- Example:
String str1 = "apple"; String str2 = "banana"; int result = (str2); // result is less than 0 because "apple" comes before "banana" lexicographically
-
-
compareToIgnoreCase()
method:-
compareToIgnoreCase()
Method is also used to compare two strings lexicographically and return an integer value. andcompareTo()
The difference is,compareToIgnoreCase()
Methods are not case-sensitive when comparing. - Example:
String str1 = "apple"; String str2 = "Banana"; int result = (str2); // result is less than 0 because "apple" comes before "Banana" in lexicographic order regardless of case
-
These methods compare strings based on Unicode values. When comparing strings, the JVM will compare the Unicode values of the characters at corresponding positions in the string one by one. If different characters are found at a certain position, the overall size relationship is determined based on the Unicode values of those characters.
In general,compareTo()
andcompareToIgnoreCase()
Methods are very useful tools when comparing and sorting strings, and can help us determine the positional relationship of strings in lexicographic order.
4. Intercept string
In Java,String
classsubstring()
Method is used to extract a substring from the original string. This method has two overloaded forms, one is to extract the substring by specifying the starting index, and the other is to extract the substring by specifying both the starting index and the ending index. The following is an introduction to these two forms:
-
substring(int beginIndex)
method:- This method accepts an integer parameter
beginIndex
, indicating the starting index of the substring (includingbeginIndex
corresponding characters). - Returns a new string containing the
beginIndex
All characters up to the end of the original string. - Example:
String str = "Hello, World!"; String subStr = (7); // subStr equals "World!"
- This method accepts an integer parameter
-
substring(int beginIndex, int endIndex)
method:- This method accepts two integer parameters
beginIndex
andendIndex
, respectively representing the starting index of the substring (includingbeginIndex
corresponding character) and the ending index (excludingendIndex
corresponding characters). - Returns a new string contained in
beginIndex
andendIndex
characters (excludingendIndex
corresponding characters). - Example:
String str = "Hello, World!"; String subStr = (7, 12); // subStr equals "World"
- This method accepts two integer parameters
It should be noted thatbeginIndex
represents the starting index of the substring, whileendIndex
is not included in the substring. If you need to extract the entire string, you can not specifyendIndex
, which will extract frombeginIndex
All characters to the end of the string.
in usesubstring()
method, you must ensure that the provided index is within the valid range, otherwise it will throwIndexOutOfBoundsException
abnormal. This method is often used when processing strings, and can help us extract the required substrings from a longer string.
5. Remove leading and trailing spaces
In Java,String
in classtrim()
method andsplit()
The method is a commonly used string processing method, used to remove whitespace characters from a string and split the string into substrings. Here is their introduction:
-
trim()
method:-
trim()
This method is used to remove leading and trailing whitespace characters (spaces, tabs, newlines, etc.) from a string and return a new string without modifying the original string. - Example:
String str = " Hello, World! "; String trimmedStr = (); // trimmedStr equals "Hello, World!"
- Notice:
trim()
This method only removes the leading and trailing whitespace characters, and the middle whitespace characters will not be deleted.
-
6. Separate strings with specified characters
split()
method:
-
split()
Method splits a string into substrings based on the specified delimiter and returns an array of strings. - You can provide a regular expression as the delimiter, or directly provide a regular string as the delimiter.
- This method supports passing in a limit parameter to limit the length of the split string array.
- Example:
String str = "apple,banana,grape,orange";
String[] fruits = (",");
// The fruits array contains ["apple", "banana", "grape", "orange"]
// Use restriction parameters to split up to two substrings
String[] firstTwoFruits = (",", 2);
// firstTwoFruits array contains ["apple", "banana,grape,orange"]
- If the delimiter is at the beginning or end of the string, then
split()
Method produces an empty string in the result array. If you don't want to include empty strings, you can use regular expressions in conjunction with\\s*,\\s*
to remove possible spaces.
These two methods are frequently used string processing methods in Java. They can help us clean and split strings, making string processing more convenient and flexible.
7. Replacement
In Java,String
in classreplace()
andreplaceAll()
Both methods are used to replace characters or substrings in a string, but they have some differences. Here is their introduction:
-
replace()
method:-
replace()
Method used to replace the specified character or character sequence with a new character or character sequence. - This method has two overloaded forms: one that accepts two character parameters and the other that accepts two string parameters.
- Example:
String str1 = "Hello, World!"; String replacedStr1 = ('o', '*'); // replacedStr1 equals "Hell*, W*rld!" String str2 = "apple,banana,orange"; String replacedStr2 = (",", ";"); // replacedStr2 equals "apple;banana;orange"
-
-
replaceAll()
method:-
replaceAll()
Method used to replace a character or sequence of characters in a string using a regular expression. - This method accepts two parameters: a regular expression to match and a string to replace the matched content.
- Example:
String str = "Hello, World!"; String replacedStr = ("o", "*"); // replacedStr equals "Hell*, W*rld!"
- The power of regular expressions is that they can implement more complex matching and replacement logic, such as replacing all numbers or a specific pattern of characters.
- The first parameter of replaceAll is the replacement rule.
- Example:
String str="hello world zhangsan"; String temp=("world|zhangsan","Java");
-
Regarding the difference between the two:
-
replace()
The parameters of the method are ordinary characters or character sequences. Regular expressions are not supported, so only specific characters or substrings can be replaced. -
replaceAll()
The first parameter of the method is a regular expression, so more flexible and complex matching and replacement operations can be performed. This makesreplaceAll()
A wider range of patterns can be replaced, not just specific character or substring replacements.
By usingreplace()
andreplaceAll()
Method, we can easily perform replacement operations on strings to achieve various processing needs.
8. Convert case
In Java,toLowerCase()
andtoUpperCase()
Method is a method used to convert a string to lowercase and uppercase forms. Here is their introduction:
-
toLowerCase()
method:-
toLowerCase()
Method used to convert all characters in a string to lowercase. - This method does not modify the original string, but returns a new string in which all characters have been converted to lowercase.
- Example:
String str = "Hello, World!"; String lowerCaseStr = (); // lowerCaseStr equals "hello, world!"
-
-
toUpperCase()
method:-
toUpperCase()
Method used to convert all characters in a string to uppercase. - Similar to
toLowerCase()
method,toUpperCase()
The original string is not modified, but a new string is returned with all characters converted to uppercase. - Example:
String str = "Hello, World!"; String upperCaseStr = (); // upperCaseStr equals "HELLO, WORLD!"
-
These two methods are very practical and can be used to uniformly convert the string content into the corresponding upper and lower case form without changing the original string. These transformation operations are common in many text processing scenarios.
Some things to note:
- Both methods consider conversion to the corresponding upper and lower case for each character. In some languages or special cases, this conversion may produce some unexpected results, so it needs to be used with caution.
- When performing case conversion, you need to consider the special characters and conversion rules of different languages to ensure the accuracy of the conversion.
9. Query the starting position of a string in the string
In Java,indexOf()
andlastIndexOf()
Method used to find the first and last occurrence of a specific substring in a string. Here is their introduction:
-
indexOf()
method:-
indexOf()
Method used to find the first occurrence of a specified substring in a string. - Optionally provide a substring and (optional) starting search position as arguments.
- If the substring is found, returns the index of the first occurrence of the substring; if not found, returns -1.
- Example:
String str = "Hello, World!"; int index = ("o"); // returns 4 because the first "o" appears at index 4
-
-
lastIndexOf()
method:-
lastIndexOf()
Method used to find the last occurrence of a specified substring in a string. - Optionally provide a substring and (optional) starting search position as arguments.
- Returns the index of the last occurrence of the substring if it is found, or -1 if it is not found.
- Example:
String str = "Hello, World!"; int index = ("o"); // returns 8 because the last "o" appears at index position 8
-
These two methods are useful for finding the position of a specific substring in a string. If you want to know the position of a substring in a string or need to locate a specific character,indexOf()
andlastIndexOf()
It's a very convenient tool. Remember, indexing starts at 0, i.e. the first character has index 0.
10. Query whether the string contains another substring
In Java,contains()
Method used to check whether a string contains another specified substring. Here is its introduction:
-
contains()
method:-
contains()
Method used to check whether a string contains a specified substring. -
Returns if it contains the specified substring
true
;If not included, returnfalse
。 -
This method is case-sensitive, so the case of characters is taken into account when comparing.
-
Example:
String str = "Hello, World!"; boolean contains1 = ("Hello"); // Returns true because the string contains the substring "Hello" boolean contains2 = ("world"); // Returns false because the string does not contain the substring "world" (case mismatch)
-
contains()
Methods are typically used to check whether a string contains another string, in order to determine whether a specific content is present when making logical judgments or performing some operations. As part of the String class, this method is a very commonly used function in string operations.
Please note thatcontains()
The method only checks whether the specified substring is contained, but does not provide the position of the substring. If you need to find the position of a substring you should useindexOf()
orlastIndexOf()
method.
11. Query whether the string starts with a substring or ends with a substring
In Java,startsWith()
method andendsWith()
Method used to check whether the string starts with the specified prefix or ends with the specified suffix. Here is their introduction:
-
startsWith()
method:-
startsWith()
Method used to check if a string starts with the specified prefix. - Accepts one argument, the prefix string to check.
- Returns if the string begins with the specified prefix
true
; Otherwise returnfalse
。 - Comparisons are case-sensitive.
- Example:
String str = "Hello, World!"; boolean startsWithHello = ("Hello"); // Returns true because the string starts with "Hello" boolean startsWithHi = ("Hi"); // Returns false because the string does not start with "Hi"
-
-
endsWith()
method:-
endsWith()
Method used to check whether the string ends with the specified suffix. - Accepts one argument, the suffix string to check.
- Returns if the string ends with the specified suffix
true
; Otherwise returnfalse
。 - Comparisons are case-sensitive.
- Example:
String str = "Hello, World!"; boolean endsWithWorld = ("World!"); // Returns true because the string ends with "World!" boolean endsWithJava = ("Java"); // Returns false because the string does not end with "Java"
-
startsWith()
andendsWith()
Methods are often used to check specific prefixes and suffixes of strings, which is very useful when processing strings with specific formats such as file extensions and URLs. These methods provide a simple and efficient way to check the beginning and end of a string.
12. Determine whether the string is empty
In Java,isEmpty()
Method used to check whether a string is empty, that is, whether its length is 0. Here is its introduction:
-
isEmpty()
method:-
isEmpty()
The method is used to check whether the string is empty, that is, whether the length of the string is 0. -
If the string is empty, return
true
;If the string is not empty (length is greater than 0), then returnfalse
。 -
Example:
String str1 = ""; // empty string String str2 = "Hello, World!"; // non-empty string boolean empty1 = (); // Returns true because the string is empty boolean empty2 = (); // returns false because the string is not empty
-
isEmpty()
Method is usually used to check if a string contains any characters. This is a convenient method, especially when you need to ensure that the string does not contain anything. In some cases, avoiding attempts to handle empty strings can improve the robustness of your code, so this method should be used to verify that a string is empty when needed.