Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the comparison, search and replacement of Java strings

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to analyze the comparison, search and replacement of Java strings? in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

In Java, there are rich manipulation methods for string classes. For strings, our common operations are: string comparison, search, replacement, split, interception, and other operations.

In Java, there are String,StringBuffer and StringBuilder string classes. The difference between them is that the String class is immutable, while the StringBuffer and StringBuilder classes are modifiable. It should be noted that the changes here are not literal. To put it simply, for example, to implement the concatenation of two strings, for the former, suppose there is str1 = "hello" and you want to concatenate a "world" for him, then it is like this, in the process, "hello" itself has not changed, it is still in the pool. But for the latter two, suppose there is str2 = "world" and the 'Hello' is concatenated. 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 thread safe.

Next, we will illustrate some operations around strings.

First, the comparison of strings 1. The method of comparing strings

Official document description:

Public boolean equals (Object anObject)

Compares this string to the specified object. The result is true if and only if the parameter is not null and is a String object, representing the same character sequence as the object.

Parameters.

AnObject-compare the object of this String

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 whether two strings are equal. This comparison is case-sensitive. When one is a string constant, the recommended way to write it is to leave the string constant outside. The reason is that if the outer 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)); / or it is possible to write / / System.out.println (str2.equals (str1)); / / execution result / / trueString str = new String ("Hello"); / / method-System.out.println (str.equals ("Hello")); / / Mode II-System.out.println ("Hello" .equals (str)) / /-- String str = null;// mode 1 / / the execution result throws a java.lang.NullPointerException exception System.out.println (str.equals ("Hello")); / / method 2 / / execution result falseSystem.out.println ("Hello" .equals (str))

If you don't need case-sensitive comparisons, use the equalsIgnoreCase () method. This method is generally found in CAPTCHA verification.

String str1 = "hello"; String str2 = "Hello"; / / the result is falseSystem.out.println (str1.equals (str2)); / / the result is true System.out.println (str1.equalsIgnoreCase (str2)); 2 the method of compareto ()

Official document description:

Public int compareTo (String anotherString)

Compare two strings in dictionary order. The comparison is based on the Unicode value of each character in the string. The character sequence represented by the String object is compared in lexicographical order with the character sequence represented by the parameter string. If the String object is arranged before the parameter string in lexicographical order, the result is a negative integer. The result is a positive integer if the String object follows the parameter string in lexicographical order. If the strings are equal, the result is zero; compareTo returns 0, while the equals (Object) method returns true.

If they do not have different index positions, the shorter strings come before the longer strings in dictionary order. In this case, compareTo returns the difference in string length-that is, value: this.length ()-anotherString.length ()

Parameters.

AnotherString-the String to compare.

Result

If the parameter string is equal to this string, the value is 0; a value is less than 0 if the dictionary of the string is smaller than the string parameter; if the dictionary size of the string is larger than the string parameter, the value is greater than 0.

The compareTo () method is a very important method in the String class. This method returns an integer, and the data returns three types of content according to the size relationship: 1. Equality: returns 0. two。 Less than: the returned content is less than 0. 3. Greater than: the returned content is greater than 0. CompareTo () is a method that can distinguish the relationship between size and size, and it is a very important method in the String method. Its comparative size rule, summed up into three words "dictionary order" is equivalent to determining whether two strings are before or after a dictionary. First compare the size of the first character (determined by the value of unicode), and if it is a tie, compare the rest 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 ("Liu" .compareto ("Yang")) / / the result of comparison is between unicode code 2. The string lookup method is 1 ~ ().

Official document description:

Public boolean contains (CharSequence s)

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

Parameters.

S-order of search

Result

True if the string contains s, false otherwise

Used to determine whether a substring exists.

String str = "helloworld"; System.out.println (str.contains ("world")); / / true2, indexOf () method

Official document description:

Public int indexOf (int ch)

Returns the index within the string where the specified character appears for the first time. If the character sequence represented here by the character ch with the value occurs the object where the first event of String occurs, the index (Unicode code) is returned. If there are no such characters in this string,-1 is returned.

Parameters.

Ch-one character (Unicode code point).

Result

The index that occurs for the first time in the character sequence represented by the object, or-1 if the character does not occur.

Looks up the location of the specified string from scratch, returns the starting index of the location (starting at 0), and returns-1 if not.

String str = "helloworld"; System.out.println (str.indexOf ("world")); / / 5Index System.out.println (str.indexOf ("bit")) at the beginning of w; / /-1, no 3GI startsWith () and endsWith () methods are found

Public boolean startsWith (String prefix)

Tests whether the string begins with the specified prefix.

Parameters.

Prefix-prefix.

Result

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

Public boolean endsWith (String suffix)

Tests whether the string ends with the specified suffix.

Parameters.

Suffix-suffix.

Result

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

String str = "* * @ @ helloworldly!"; System.out.println (str.startsWith ("* *")); / / true System.out.println (str.startsWith ("@ @", 2)); / / ture System.out.println (str.endsWith ("!!")); / / true III, 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 substitution.

Note that replacing the backslash (\) and the dollar sign ($) in a string may cause the result to be different from that when it is considered a literal replacement string; see Matcher.replaceAll. If necessary, use Matcher.quoteReplacement (java.lang.String) to suppress the special meaning of these characters.

Parameters.

Regex-the regular expression to match this string

Replacement-to replace each matching string

Result

Obtained String

Abnormal

PatternSyntaxException-if the syntax of the regular expression is invalid

The replaceAll () method will replace all the specified contents. To replace the first letter, use the replaceFirst () method. Note that because the string is an immutable object, substitution does not modify the current string, but produces a new string.

String str = "helloworld"; System.out.println (str.replaceAll ("l", "_")); / / he__owor_dSystem.out.println (str.replaceFirst ("l", "_")); / / he_ world 4, string splitting

String splitting is a common operation, such as using BufferedReader for fast input and output of data, at this time, enter the string first, split and transform it into int and other data types.

Split () method

Public String [] split (String regex)

Splits this string into matches for the given regular expression.

This method works by calling the two-parameter split method with a given expression and a limit parameter of zero. Therefore, the trailing empty string is not included in the result array.

Parameters.

Regex-delimited regular expressions

Result

An array of strings calculated by matching the string around a given regular expression

Abnormal

PatternSyntaxException-if the syntax of the regular expression is invalid

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

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

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]); }

Fifth, 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.

Parameters.

BeginIndex-start indexing (inclusive).

Result

The specified substring.

Abnormal

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

This method can truncate part of the content from a complete string from the specified index to the end. What we should pay attention to is: 1. The index starts at 0. 2. Pay attention to the writing of the opening interval before and after closing. Substring (0,5) indicates a character containing subscript 0, but not subscript 5.

String str = "helloworld"; System.out.println (str.substring (5)); / / worldSystem.out.println (str.substring (0,5)); / / Hello6, other common string manipulation methods

These common operations such as: get the length of the string, remove the space on both sides of the string, retain the space in the middle, string case conversion, string inversion.

1pr trim () method

Official document description:

Public String trim ()

Returns a string whose value is this string and removes any leading and trailing spaces.

If this String object represents a sequence of empty characters, or if the first and last character String objects of the representative character sequence have codes greater than'\ u0020'(space characters), this reference String is returned.

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

Otherwise, make k the'\ u0020'of the first character in a string whose code is greater than'\ u0020', and m is the'\ u0020'of the last character in a string whose code is greater than'\ u0020'. A String object is returned that represents the substring of the string, starting with the character at index k and ending with the character ending with index m, resulting in this.substring (k, m + 1).

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

Result

A string whose value is this string, excluding any leading and trailing spaces, or if the string does not have leading or trailing spaces.

The trim () method removes white space 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 () + "]")

2the methods of toLowerCase () and UpperCase ()

Official document description:

Public String toUpperCase (Locale locale)

Parameters.

Locale-case conversion rules that use this locale

Result

String, convert to uppercase.

Public String toLowerCase (Locale locale)

Parameters.

Locale-case conversion rules that use this locale

Result

String, convert to lowercase.

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

Official document description:

Public int length ()

Returns the length of this string. The length is equal to the number 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 attribute, while the length () method is used in String.

String str = "hello%$$%@#$%world ha ha"; System.out.println (str.length ()); / / 243 reverse () method

The String class does not provide the reverse () method, which exists in the StringBuffer and StringBuilder classes. To use this method, new the objects generated by them to use. StringBuffer and StringBuilder are very similar, and here, they are illustrated by StringBuffer.

Official document description:

Public StringBuilder reverse ()

Causes the character sequence to be replaced by the opposite of the sequence. If the sequence contains any alternative pairs, they are treated in reverse as a single character.

Result

A reference to this object

StringBuffer sb = new StringBuffer ("helloworld"); System.out.println (sb.reverse ()); / / dlrowolleh on how to analyze the comparison, search and replacement of Java strings and other operational questions are shared here. I hope the above content can be of some help to everyone. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report