SoFunction
Updated on 2025-03-05

Various methods commonly used in String class in Java (example details)

The following introduces several common methods for strings.

Introduction to String class

In Java,StringA class is a class representing a string, with the following characteristics:

  • ImmutabilityStringObjects are immutable once created, that is, their values ​​cannot be changed after creation. Any rightStringThe object modification operation will actually create a new oneStringObject.

  • String pool: A string pool in Java is a special memory area used to store string constants. When creating a string, it first checks whether a string of the same value already exists in the string constant pool, and if so, returns a string reference in the pool without creating a new object.

  • Compare: The string can be passedequals()Method to compare whether their content is the same. In Java, useequals()Compare string content instead of using==To compare whether the object references are equal.

  • Security brought by immutability: Since strings are immutable, they can be safely passed to methods as parameters to avoid being modified unexpectedly.

  • performance: Since strings are immutable, they can be cached and reused, and can be used during string concatenation.StringBuilderorStringBufferClasses to improve performance.

  • String operation methodStringClasses provide many methods for manipulating strings, such aslength()charAt(index)substring()etc. These methods can help developers easily handle strings.

Overall,StringClasses play an important role in Java and are one of the classes that are often used in development. Its immutability and string pooling characteristics make string processing safer and more efficient.

1. Splicing:

In Java,StringClassicconcat()Methods and+Operators are all used to splice strings. Both methods can concatenate two strings together to form a new string, but there are some slight differences:

  • concat()method:concat()The method isStringAn instance method of the class, used to concatenate the specified string to the end of the string that calls the method. It returns a new string object, the original string is not affected. For example:
String str1 = "Hello";
String str2 = "World";
String result = (str2); // The result is "HelloWorld"
  • +Operator+Operators can also be used for string stitching. They can concatenate two strings (can also concatenate strings and other data types, and will 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 the syntax form, using operators+When it is actually throughStringClassicconcat()The method is called implicitly to implement string stitching.

In actual development,+Operators are more commonly used because they are 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, forming complete output information.

In general, whether it is usedconcat()Method or+The ultimate goal of the operator is to concatenate multiple strings into a new string.

2. Compare whether the string is equal:

When we want to compare whether two strings are the same, we should pay special attention to whether the contents of the string are actually the same. Must useequals()Method but not 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 use==andequals()Comparison istrue, but in fact it is just that the Java compiler will automatically put all the same strings into a constant pool as an object during the compilation period. Naturallys1ands2The quotes are the same.

So, this==Compare backtrueIt's purely coincidental. Change the writing method,==Comparison will fail:

// String
public class Main {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO".toLowerCase();
        (s1 == s2);
        ((s2));
    }
}

Conclusion: Two string comparisons must always be usedequals()method.

3. Compare the size of the string:

In Java,StringClass providedcompareTo()Methods andcompareToIgnoreCase()Methods are used to compare the size relationship between strings. These two methods return integer values, which represent dictionary-sorted relationships between two strings. Here is their introduction:

  • compareTo()method:

    • compareTo()The method is used to compare two strings in dictionary order and return an integer value, and returns different values ​​according to the comparison results:
      • If the call string is smaller than the parameter string, a negative integer is returned.
      • If the call string is larger than the parameter string, a positive integer is returned.
      • If the two strings are equal, return 0.
    • Example:
String str1 = "apple";
String str2 = "banana";
int result = (str2);
// result Less than 0,because "apple" Ranking in dictionary order "banana" Before
  • compareToIgnoreCase()method:

  • compareToIgnoreCase()The method is also used to compare two strings in dictionary order and return an integer value. andcompareTo()The difference is,compareToIgnoreCase()Methods are case-insensitive when comparing.
  • Example:
String str1 = "apple";
String str2 = "Banana";
int result = (str2);
// result Less than 0,because "apple" In ignoring case and ranking in dictionary order "Banana" Before

These methods compare strings based on Unicode values. When comparing strings, the JVM compares the Unicode values ​​of characters at corresponding positions in the string one by one. If different characters are found at a certain location, the overall size relationship is determined based on the Unicode values ​​of these characters.

Overall,compareTo()andcompareToIgnoreCase()Methods are very useful tools when comparing and sorting strings, which can help us determine the positional relationship of strings in dictionary order.

4. Intercept the string

In Java,StringClassicsubstring()Method is used to extract substrings from original strings. This method has two overloaded forms. One is to extract the substring by specifying the start index, and the other is to extract the substring by specifying the start index and the end index at the same time. Here is an introduction to these two forms:

  • substring(int beginIndex)method:

    • This method accepts an integer parameterbeginIndex, represents the starting index of the substring (includingbeginIndexRelevant characters).
    • Returns a new string containing frombeginIndexAll characters to the end of the original string.
    • Example:
String str = "Hello, World!";
String subStr = (7); // subStr equal "World!"
  • substring(int beginIndex, int endIndex)method:

    • This method accepts two integer parametersbeginIndexandendIndex, respectively represent the starting index of the substring (includingbeginIndexCorresponding characters) and end index (excludingendIndexRelevant characters).
    • Returns a new string, contained inbeginIndexandendIndexCharacters between (excludingendIndexRelevant characters).
    • Example:
String str = "Hello, World!";
String subStr = (7, 12); // subStr equal "World"

It should be noted thatbeginIndexRepresents the start index of the substring, andendIndexis not included in the substring. If you need to extract the entire string, you can not specifyendIndex, this will extract frombeginIndexAll characters to the end of the string.

In usesubstring()When a method, it is necessary to ensure that the provided index is within the valid range, otherwise it will be thrownIndexOutOfBoundsExceptionException. This method is often used when processing strings and can help us extract the required substrings from a longer string.

5. Remove the beginning and end spaces

In Java,StringIn the classtrim()Methods andsplit()The method is a commonly used string processing method, which is used to remove whitespace characters of a string and split the string into substrings. Here is their introduction:

  • trim()method:

     
    • trim()The method is used to remove the beginning and end of the string (spaces, tabs, line breaks, etc.), and returns a new string without modifying the original string.
    • Example:
String str = "   Hello, World!    ";
String trimmedStr = (); // trimmedStr equal "Hello, World!"
  • Notice:trim()The method only removes the beginning and end of the white space characters, and the middle white space characters will not be deleted.

6. Separate strings with specified characters

split()method

  • split()The method splits the string into substrings based on the specified delimiter and returns an array of strings.
  • You can provide a regular expression as a separator, or directly provide a normal string as a separator.
  • This method supports passing in a restriction parameter to limit the length of the string array obtained by splitting.
  • Example:
String str = "apple,banana,grape,orange";
String[] fruits = (",");
// The fruits array contains ["apple", "banana", "grape", "orange"]// Use restricted parameters to split up to two substringsString[] firstTwoFruits = (",", 2);
// firstTwoFruits Array contains ["apple", "banana,grape,orange"]
  • If the delimiter is at the beginning or end of the string,split()The method will produce an empty string in the result array. If you do not want to include an empty string, you can use regular expressions in combination.\\s*,\\s*To remove possible spaces.

These two methods are often used in Java, which can help us clean, segment strings and other operations, making string processing more convenient and flexible.

7. Replacement

In Java,StringIn the classreplace()andreplaceAll()Methods are all used to replace characters or substrings in strings, but they have some differences. Here is their introduction:

  • replace()method:

    • replace()Method is used to replace the specified character or character sequence with a new character or character sequence.
    • This method has two overloaded forms: one accepts two character parameters and the other 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 equal "apple;banana;orange"
  • replaceAll()method:

  • replaceAll()Methods are used to replace characters or sequences of characters in strings with regular expressions.
  • This method takes two parameters: a regular expression for matching and a string for replacing the matched content.
  • Example:
String str = "Hello, World!";
String replacedStr = ("o", "*"); // replacedStr equal "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 characters in a specific pattern.
  • The first parameter to 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 and do not support regular expressions, so they can only replace specific characters or substrings.
  • replaceAll()The first parameter of the method is a regular expression, so it can perform more flexible and complex matching and replacement operations. This makesreplaceAll()A wider pattern can be replaced, not limited to specific character or substring replacements.

By usingreplace()andreplaceAll()Method, we can easily perform replacement operations on strings, thereby achieving various processing needs.

8. Convert case

In Java,toLowerCase()andtoUpperCase()Methods are methods used to convert strings to lowercase and uppercase forms. Here is their introduction:

  • toLowerCase()method:

    • toLowerCase()Methods are used to convert all characters in a string to lowercase.
    • This method does not modify the original string, but returns a new string where all characters are converted to lowercase.
    • Example:
String str = "Hello, World!";
String lowerCaseStr = (); // lowerCaseStr equal "hello, world!"
  • toUpperCase()method:

    • toUpperCase()Method is used to convert all characters in a string to uppercase.
    • Similar totoLowerCase()method,toUpperCase()It also does not modify the original string, but returns a new string where all characters are converted to capitalization.
    • Example:
String str = "Hello, World!";
String upperCaseStr = (); // upperCaseStr equal "HELLO, WORLD!"

These two methods are very practical and can be used to 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:

  • These two methods consider converting to the corresponding case form of each character. In some languages ​​or in special cases, such conversions may produce some unexpected results and therefore require caution.
  • When performing case conversion, special characters and conversion rules for different languages ​​need to be considered to ensure the accuracy of the conversion.

9. Query the starting position of a string in the query string

In Java,indexOf()andlastIndexOf()Methods are used to find the first occurrence and the last occurrence of a specific substring in a string. Here is their introduction:

  • indexOf()method

    • indexOf()Method is used to find the first occurrence of a specified substring in a string.
    • You can choose to provide substring and (optional) starting search position as parameters.
    • If a substring is found, the index of the first occurrence of the substring is returned; if not found, -1 is returned.
    • Example:
String str = "Hello, World!";
int index = ("o"); // return 4,Because the first "o" Appears at index position 4
  • lastIndexOf()method:

    • lastIndexOf()Method is used to find the last occurrence of the specified substring in a string.
    • You can choose to provide substring and (optional) starting search position as parameters.
    • If a substring is found, the index of the last occurrence of the substring is returned; if not found, the -1 is returned.
    • Example:
String str = "Hello, World!";
int index = ("o"); // return 8,Because the last one "o" Appears at index position 8

These two methods are useful for finding the location of a specific substring in a string. If you want to know where the substring is in the string or where a specific character needs to be located,indexOf()andlastIndexOf()It is a very convenient tool. Remember that the index is counted from 0, i.e. the index of the first character is 0.

10. Query whether another substring is included in the string

In Java,contains()Method is used to check whether a string contains another specified substring. Here is its introduction:

  • contains()method:

    • contains()Method is used to check whether the string contains the specified substring.

    • If the specified substring is contained, returntrue; 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"); // Return true because the string contains the substring "Hello"boolean contains2 = ("world"); // return false,Because the string does not contain substrings "world"(Case mismatch)

contains()Methods are usually used to check whether a string contains another string, so as to determine whether a specific content exists when logically judging or performing certain 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 contains, and does not provide the location of the substring. If you need to find the location of the substring, you should useindexOf()orlastIndexOf()method.

11. Check whether the string starts with a substring or ends with a substring

In Java,startsWith()Methods andendsWith()Method is used to check whether a string begins with a specified prefix or ends with a specified suffix. Here is their introduction:

  • startsWith()method:

    • startsWith()Method is used to check whether a string begins with the specified prefix.
    • Accepts an argument, the prefix string to be checked.
    • If the string begins with the specified prefix, returntrue; Otherwise returnfalse
    • Comparisons are case sensitive.
    • Example:
String str = "Hello, World!";
boolean startsWithHello = ("Hello"); // Return true, because the string starts with "Hello"boolean startsWithHi = ("Hi"); // return false,Because the string does not "Hi" beginning
  • endsWith()method:

    • endsWith()Method is used to check whether the string ends with the specified suffix.
    • Accepts an argument, the suffix string to be checked.
    • If the string ends with the specified suffix, returntrue; Otherwise returnfalse
    • Comparisons are case sensitive.
    • Example:
String str = "Hello, World!";
boolean endsWithWorld = ("World!"); // Return true, because the string ends with "World!"boolean endsWithJava = ("Java"); // return false,Because the string does not "Java" Ending

startsWith()andendsWith()Methods are often used to check specific prefixes and suffixes of strings, which are very useful when handling strings with specific formats such as file extensions, URLs, etc. 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()The method is 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, returntrue; If the string is not empty (length greater than 0), returnfalse

    • Example:

String str1 = ""; // Empty stringString str2 = "Hello, World!"; // Non-empty stringboolean empty1 = (); // Return true because the string is emptyboolean empty2 = (); // return false,Because the string is not empty

isEmpty()Methods are usually used to check whether a string contains any characters. This is a convenient method, especially when you need to make sure that the string does not contain anything. In some cases, avoiding trying to deal with empty strings can improve the robustness of your code, so this method should be used to verify that the string is empty when needed.

This is the end of this article about the various commonly used methods of String class in Java. For more related contents of common methods of String class, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!