Common operations on Java strings

In Java, the string class provides a wealth of operation methods. For strings, our common operations are: string comparison, search, replacement, splitting, interception, and other operations.

        In Java, there are String, StringBuffer and StringBuilder string classes. The difference between them is that the String class cannot be modified, while the StringBuffer and StringBuilder classes can be modified. It should be noted that the modification here is not a literal modification. To put it simply, for example, to realize the splicing of two strings, for the former, suppose there is str1 = "hello", and you want to splicing a "world" for him, then it is like this, in this process, "hello" It hasn't changed, it's still in the pool. But for the latter two, assuming str2 = "world", to splicing ''hello'', after splicing, there is no "world" in the pool. The difference between StringBuffer and StringBuilder is that one is thread-safe and the other is not.

        Below, we describe some operations around strings.

First, the comparison of strings

1, equal() method

Official document description:

public boolean equals(Object anObject)

Compares this string with the specified object. The result is true if and only if the argument is not null and is a String object representing the same sequence of characters as this object.

parameter

anObject - the object to compare this String to

result

true if the given object represents a String equivalent to this String, otherwise false

        The equal() method in the String class is used to compare two strings for equality. This comparison is case-sensitive. When there is a string constant, the recommended way of writing is to put the string constant outside. The reason for this is that if the outside variable is null, a null pointer exception will be thrown.

String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1.equals(str2));
// 或者这样写也行
// System.out.println(str2.equals(str1)); 
// 执行结果
//true
String str = new String("Hello");
// 方式一
System.out.println(str.equals("Hello"));
// 方式二
System.out.println("Hello".equals(str));
//——————————————————————————————————————
String str = null;
// 方式一
// 执行结果 抛出 java.lang.NullPointerException 异常
System.out.println(str.equals("Hello")); 
// 方式二
// 执行结果 false
System.out.println("Hello".equals(str));  

        If a case-sensitive comparison is not required, use the equalsIgnoreCase() method. This method is generally seen in the verification code verification.

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

2, compareTo() method

Official document description:

public int compareTo(String anotherString)

Compare two strings lexicographically . The comparison is based on the Unicode value of each character in the string. The sequence of characters represented by this String object is compared lexicographically to the sequence of characters represented by the argument string. If the String object lexicographically precedes the argument string, the result is a negative integer. The result is a positive integer if the String object follows the argument string lexicographically. If the strings are equal, the result is zero; compareTo returns 0, and the equals(Object) method will return true.

Without their different index positions, the shorter strings lexicographically precede the longer strings. In this case, compareTo returns the difference in string length - ie the value: this.length() - anotherString.length()

parameter

anotherString - the String to compare against.

result

The value is 0 if the argument string is equal to this string; a value less than 0 if the dictionary of this string is smaller than the string argument; the value is greater than 0 if the dictionary size of this string exceeds the size of the string argument.

        The compareTo() method in the String class is a very important method. This method returns an integer. The data will return three types of content according to the size relationship: 1. Equal: return 0. 2. Less than: return content less than 0. 3 . Greater than: The returned content is greater than 0. compareTo() is a method that can distinguish the size relationship, and it is a very important method in the String method. Its size comparison rules, summed up into three words " lexicographical order " is equivalent to determining whether two strings are in front or behind a dictionary. First compare the size of the first character (determined according to the value of unicode), if there is no winner, compare the following contents in turn.

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("刘".compareTo("杨")); //比较结果介于unicode码

Second, string search

1, contains() method

Official document description:

public boolean contains(CharSequence s)

Returns true if and only if this string contains the specified sequence of char values.

parameter

s - the order in which to search

result

true if this string contains s, false otherwise

        Used to determine whether a substring exists.

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

2, indexOf() method

Official document description:

public int indexOf(int ch)

Returns the index within the string of the first occurrence of the specified character. The index (Unicode code) is returned if the first occurrence of the String event occurs in the character sequence represented by the character ch of the value here. Returns -1 if there are no such characters in this string.

parameter

ch - a character (Unicode code point).

result

The index of the first occurrence of the character in the sequence of characters represented by this object, or -1 if the character does not occur.

        Find the position of the specified string from the beginning, and return the starting index of the position (starting from 0) if it is found, and return -1 if it cannot be found.

String str = "helloworld" ; 
System.out.println(str.indexOf("world")); // 5,w开始的索引
System.out.println(str.indexOf("bit")); // -1,没有查到

3, startsWith() and endsWith() methods

public boolean startsWith(String prefix)

Tests whether this string begins with the specified prefix.

parameter

prefix - the prefix.

result

Returns true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; otherwise false. Also note that true if the argument is an empty String or equal to the String object will be returned as determined by the equals(Object) method.

public boolean endsWith(String suffix)

Tests whether this string ends with the specified suffix.

parameter

suffix - suffix.

result

true if the character sequence represented by the argument is a suffix of the character sequence represented by this object; false otherwise. Note that the result will be true if the argument is the empty String or equal to the String object as determined by the equals(Object) method.

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

Three, string replacement

replaceAll() method

public String replaceAll(String regex,String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement .

Note that backslashes ( \ ) and dollar signs ( $ ) in replacement strings may cause different results than if they were treated as literal replacement strings; see Matcher.replaceAll . If necessary, use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters.

parameter

regex - the regular expression to match this string

replacement - the string to replace each match

result

the resulting String

abnormal

PatternSyntaxException - if the syntax of the regular expression is invalid

        The replaceAll() method will replace all the specified content. To replace the first letter, use the replaceFirst() method. Note that since strings are immutable objects, replacement does not modify the current string, but produces a new string.

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

Fourth, string splitting

        The splitting of strings is a common operation. For example, when using BufferedReader for fast input and output of data, at this time, input strings first, split them, and convert them into data types such as int.

split() method

public String[] split(String regex)

Splits this string into matches of the given regular expression .

The method works by calling the two-argument split method with the given expression and the restriction argument to zero. Therefore, trailing empty strings are not included in the resulting array.

parameter

regex - delimited regular expression

result

An array of strings computed by matching this string around the given regular expression

abnormal

PatternSyntaxException - if the syntax of the regular expression is invalid

         In addition, some special characters may not be correctly segmented as separators, and the escape symbol \\ needs to be added. 1. The characters "|", "*", "+" must be escaped, preceded by "\". 2. If there are multiple separators in a string, you can use "|" as a hyphen .

String str = "hello world hello People" ; 
String[] result = str.split(" ") ; // 按照空格拆分
for(String s: result) { 
 System.out.println(s); 
} 

String str = "192.168.1.1" ; 
String[] result = str.split("\\.") ; 
for(String s: result) { 
 System.out.println(s); 
}
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]); 
}

 

Five, string interception

substring() method

Official document description:

public String substring(int beginIndex)

Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of the string.

parameter

beginIndex - the start index (inclusive).

result

the specified substring.

abnormal

IndexOutOfBoundsException     if beginIndex is negative or greater than the length of this String object.

        This method can extract part of the content from a complete string, from the specified index to the end. It should be noted that: 1. The index starts from 0. 2. Pay attention to the writing of the front-closed and back-open interval, substring(0, 5) means the character containing the subscript 0, excluding the subscript 5.

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

Six, other common operation methods of strings

        These common operation methods are: get the length of the string, remove the spaces on both sides of the string, keep the spaces in the middle, convert the case of the string, and reverse the string.

1, trim() method

Official document description:

public String trim()

Returns a string whose value is this string, with any leading and trailing spaces removed.

If this String object represents an empty character sequence, or if the first and last characters of the character sequence represented by this String object have codes greater than '\u0020' (the space character), then this reference String is returned as the object.

Otherwise, if there are no characters in the string greater than '\u0020', return a String object representing the empty string.

Otherwise, let k be '\u0020' for the first character in strings with codes greater than '\u0020' and m be '\u0020' for the last character in strings with codes greater than '\u0020'. will return a String object representing a substring of this string, starting with the character at index k and ending with the character at index m , resulting in this.substring(k, m + 1) .

This method can be used to trim whitespace (as defined above) from the beginning and end of a string.

result

A string whose value is this string, stripped of any leading and trailing spaces, or the string if the string has no leading or trailing spaces.

        The trim() method removes whitespace characters (spaces, newlines, tabs, etc.) from the beginning and end of the string.

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

2, toUpperCase() and toLowerCase() methods

Official document description:

public String toUpperCase(Locale locale)

parameter

locale - the case conversion rules to use with this locale

result

String, converted to uppercase.

public String toLowerCase(Locale locale)

parameter

locale - the case conversion rules to use with this locale

result

String , converted to lowercase.

String str = " hello%$$%@#$%world 哈哈哈 " ; 
System.out.println(str.toUpperCase()); // HELLO%$$%@#$%WORLD 哈哈哈 
System.out.println(str.toLowerCase()); // hello%$$%@#$%world 哈哈哈 

3, length() method

Official document description:

public int length()

Returns the length of this string. The length is equal to the numeric Unicode code units in the string .

result

The length of the character sequence represented by this object.

         Note: The array length uses the array name.length property, while the length() method is used in String.

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

3, reverse() method

        The String class does not provide the reverse() method, which exists in the StringBuffer and StringBuilder classes. To use this method, it is necessary to use new out of the objects generated by them. StringBuffer and StringBuilder are very similar, here, StringBuffer is used to illustrate.

Official document description:

public StringBuilder reverse()

Causes that sequence of characters to be replaced by the opposite of the sequence. If the sequence contains any surrogate pairs, they are treated as a single character for the reverse operation.

result

a reference to this object

StringBuffer sb = new StringBuffer("helloworld"); 
System.out.println(sb.reverse()); //dlrowolleh

Guess you like

Origin blog.csdn.net/Naion/article/details/122372796