Read a lot about the Java string related knowledge, here to do a more comprehensive summary, the content transferred from different places of the blog, given the source more, not listed.
In Java, String, StringBuffer, and StringBuilder are frequently used strings in programming, and the differences between them are frequently asked questions in the interview. Now summarize and see how they differ from the same.
String literal constant
stringbuffer string variable (thread safe)
StringBuilder string variable (non-thread safe)
1. Variable and immutable
The string class uses a character array to hold strings, as follows, because there is a "final" modifier, so you know that the string object is immutable.
Private final char value[];
Both StringBuilder and StringBuffer inherit from the Abstractstringbuilder class, and in the Abstractstringbuilder, they are also used to hold strings in a character array, as follows, that both of these objects are mutable.
Char[] value;
2. Whether multithreaded security
The objects in string are immutable and can be understood as constants, apparently thread-safe.
Abstractstringbuilder is the common parent of StringBuilder and StringBuffer, and defines some basic operations for strings, such as expandcapacity, append, insert, indexof, and other public methods.
StringBuffer is thread-safe because it adds a synchronous lock to a method or a synchronous lock on a method that is called. See the following source code:
publicsynchronizedreverse() { super.reverse(); returnthis;}publicintindexOf(String str) { return0//存在 public synchronized int indexOf(String str, int fromIndex) 方法}
StringBuilder does not have a synchronous lock on the method, so it is non-thread safe.
3.StringBuilder and StringBuffer in common
StringBuilder and StringBuffer have public parent class Abstractstringbuilder (abstract Class).
One of the differences between an abstract class and an interface is that the public methods of some subclasses can be defined in an abstract class, and subclasses only need to add new functionality, and do not need to repeat the existing methods, whereas interfaces are simply definitions of the declarations and constants of the methods.
StringBuilder, StringBuffer methods will call public methods in Abstractstringbuilder, such as Super.append (...). Just stringbuffer will add synchronized keywords to the method and synchronize.
Finally, if the program is not multithreaded, then using StringBuilder is more efficient than stringbuffer.
4. Common methods of String
4.1. Initialization of a String object
Because string objects are particularly common, Java provides a simplified, special syntax for initializing a string object in the following format:
String s = “abc”; s = “Java语言”;
In fact, according to the standard object-oriented syntax, its format should be:
String s = new String(“abc”); s = new String(“Java语言”);
Only in terms of object-oriented standard syntax, there is a great waste of memory usage. For example, string s = new String ("abc"), actually creates two string objects, one is an "ABC" object, is stored in a constant space, and one is the space requested for the object s using the New keyword.
4.2 Gets the character value of the specified index
The function of the Charat method is to get the specified character in the string by index value (the index value of the first character in the string is 0, the second character's index value is 1, and so on). For example:
String s = “abc”; char c = s.chatAt(1);
The value of the variable c is ' B '.
4.3 Comparing the size of two strings
The CompareTo method compares the size of two strings by comparing the character encoding of each character in turn. The first character of the two string is compared first, if the character encoding of the first string is greater than the character encoding of the second string, the value greater than 0 is returned, and if less than 0 is returned, if equality compares subsequent characters, if the character encoding in two strings is exactly the same, 0 is returned. For example:
String s = "abc";
String s1 = “abd”; int value = s.compareTo(s1);
Then value is a value less than 0, which is-1.
There is also a similar method in the String class Comparetoignorecase, which ignores the case of characters and compares the rules with CompareTo. For example:
String s = “aBc”; String s1 = “ABC”; int value = s. compareToIgnoreCase (s1);
Then value is 0, or two strings are equal.
4.4. Connection of Strings
The Concat method joins two strings to form a new string. For example:
String s = “abc”; String s1 = “def”; String s2 = s.concat(s1);
The value of the new string S2 generated after the connection is "abcdef", and the value of the string s and S1 does not change. If you need to concatenate multiple strings, you can use the following methods:
String s = “abc”; String s1 = “def”; String s2 = “1234”; String s3 = s.concat(s1).concat(s2);
The value of the generated new string S3 is "abcdef1234".
In fact, when actually used, the syntax provides a simpler form, that is, the use of "+" string connection. For example:
String s = “abc” + “1234”;
The value of the string s is "abc1234", which makes writing easier and more intuitive. and using "+" to connect, you can not only connect strings, but also connect other types. However, there is at least one content that participates in a connection when a connection is required to be a string type. and the "+" matches the order of left-to-right, if both sides of the connected content is the base number type then according to the addition operation, if the content that participates in the connection has a string to connect according to the string.
For example:
int a = 10; String s = “123” + a + 5;
Then the value of the string s after the connection is "123105", the procedure is to concatenate the string "123" and the value of variable a, generate the string "12310", and then use the string and the number 5 to connect to produce the final result.
And the following code:
int a = 10; String s = a + 5 + “123”;
Then the value of the string s after the connection is "15123", the process of calculation is to first calculate a and the number 5, because all are numeric type is the addition operation or numeric value 15, and then use the numeric value 15 and the string "123" to connect to obtain the final result.
The following connection code is incorrect:
int a = 12; String s = a + 5 + ‘s’;
Because there is no string participating in the connection, the computed result is a numeric value that cannot be assigned a numeric value to the string s when the value is assigned.
4.5. Determine whether the contents of two string objects are the same
The Equals method determines whether the contents of a two-string object are the same. Returns true if it is the same, otherwise false. For example:
String s = “abc”; String s1 = new String(“abc”); boolean b = s.equals(s1);
The comparison with "= =" is whether the two objects store the same address in memory. For example, in the above code, if you decide:
boolean b = (s == s1);
The value of the variable B is false, because the address of the S object is the address of "ABC", and S1 uses the New keyword to request a different memory, so the memory address is not the same as the address of S "ABC", so the obtained value is false.
There is a similar method in the String class Equalsignorecase, which is the function of ignoring case to compare the contents of two strings in the same way. For example:
String s = “abc”; String s1 =”ABC”; boolean b = s. equalsIgnoreCase (s1);
Then the value of variable B is true.
4.6. Find the starting position of a specific character or string in the current string
The function of the IndexOf method is to find the starting position of a particular character or string in the current string, or 1 if it does not exist. For example:
String s = “abcded”; int index = s.indexOf(‘d’); int index1 = s.indexOf(‘h’);
Returns the position of the first occurrence of the character D in the string s, with a value of 3. Since the character H does not exist in the string s, the value of Index1 is-1. Of course, you can also find the corresponding character from a specific location, for example:
int index = s.indexOf(‘d’,4);
Finds the first occurrence of the character D in the string s from the index value 4 (including 4), then the value of index is 5.
Because IndexOf is overloaded, you can also find the starting position where a particular string appears in the current string, in the same way that you would find a character.
Another similar approach is the LastIndexOf method, which is to look forward from the end of the string to the first occurrence of the specified character or string, for example:
String s = “abcded”; int index = s. lastIndexOf(‘d’);
Then the value of index is 5.
4.7, the length of the returned string
Length method
The function of this method is to return the length of the string, which is the number of characters in the returned string. Chinese characters are also one character. For example:
String s = “abc”; String s1 = “Java语言”; int len = s.length(); int len1 = s1.length();
The value of the variable len is 3, and the value of the variable len1 is 6.
4.8. Replace all specified characters in the string
The Replace method acts by replacing all the specified characters in the string and then generating a new string. After the method call, the original string does not change. For example:
String s = “abcat”; String s1 = s.replace(‘a’,’1’);
The purpose of this code is to replace all character a in string s with character 1, and the resulting new string S1 value is "1bc1t", while the contents of the string s do not change.
If you need to replace a specified string in a string with a different string , you can use the ReplaceAll method, for example:
String s = “abatbac”; String s1 = s.replaceAll(“ba”,”12”);
The purpose of this code is to replace all the string "AB" in the string s with "12", to generate a new string "a12t12c", and the contents of the string s will not change.
If you only need to replace the first occurrence of the specified string, you can use the Replacefirst method, for example:
String s = “abatbac”; String s1 = s. replaceFirst (“ba”,”12”);
The purpose of this code is to replace only the first occurrence of the string "AB" with the string "12", the value of the string S1 is "A12tbac", and the contents of the string s are not changed.
4.9 Segmentation of Strings
The split method acts by splitting the contents of the current string with a specific string as an interval, and typically splits to get an array of strings. For example:
String s = “ab,12,df”; String s1[] = s.split(“,”);
The function of the code is to split the string s with the string "," as an interval, resulting in the splitting of the string after the number S1, whose contents are: {"AB", "B", "DF"}.
This method is the underlying method of parsing a string.
If an empty string is removed inside the string with the same contents as the interval string, the trailing empty string is ignored. For example:
String s = “abbcbtbb”; String s1[] = s.split(“b”);
The contents of the resulting string array S1 are: {"A", "" "," C "," T "}. The number of empty strings in the middle of the split is equal to the number of intermediate interval strings minus one. For example:
String s = “abbbcbtbbb”; String s1[] = s.split(“b”);
The result of the split is: {"A", "" "," "," C "," T "}. The last empty string, regardless of how many, is ignored.
If you need to limit the number of strings after splitting, you can use another split method, for example:
String s = “abcbtb1”; String s1[] = s.split(“b”,2);
The purpose of this code is to split the string s into a maximum of 2 string arrays. The result is: {"A", "CBTB1"}. If the second argument is a negative number, it splits as many strings as possible, including the trailing empty string, which is also preserved.
4.10. Take substrings in a string
The substring method is to take the "substring" in the string, the so-called "substring" that is part of the string. For example, "23" is a substring of the string "123".
The string "123" has a total of 6 substrings: "1", "2", "3", "12", "23", "123". and "32" is not a substring of the string "123".
For example:
String s = “Test”; String s1 = s.substring(2);
The function of the code is to take all characters after the index value of 2 (including) in the string s as a substring, then the value of the string S1 is "St".
If the value of the number is the same as the length of the string, an empty string is returned. For example:
String s = “Test”; String s1 = s.substring(4);
The value of the string S1 is "".
If you need to take part of the inside of a string, you can use the substring method with 2 parameters, for example:
String s = “TestString”; String s1 = s.substring(2,5);
The function of the code is to take the string s from the index value 2 (including) Start, to the index value 5 (not included) as a substring, the value of the string S1 is "StS".
The following is a simple application code that works by outputting all substrings of any string. The code is as follows:
public static void Main (string[] args) {String s = "substring example"; int len = S.length (); for (int begin = 0 ; begin < len-1 ; begin + +) {for (int end = Begin + 1 ; end <= len; end + +) {System.out.println (s.substring (begin , end)); } } }
In this code, the loop variable begin represents the starting index value of the substring that needs to be obtained, and the interval varies from the index value of the first character to the index value of the second-to-last string len-2, and end represents the ending index value of the substring that needs to be obtained, which varies from the subsequent one of the starting index value to the string length By looping through the nesting, you can iterate through all the substrings in the string.
4.11. String converted to the corresponding char array
The ToCharArray method acts like the GetBytes method, converting the string to the corresponding char array. For example:
String s = “abc”; char[] c = s.toCharArray();
The value of the character array C is: {' A ', ' B ', ' C '}.
4.12, Case conversion
The purpose of the toLowerCase method is to convert all uppercase characters in a string to lowercase. For example:
String s = “AbC123”; String s1 = s.toLowerCase();
The value of the string S1 is "abc123", and the value of the string s is not changed.
A similar approach is touppercase, which is used to convert lowercase characters in a string to the corresponding uppercase characters. For example:
String s = “AbC123”; String s1 = s. toUpperCase ();
The value of the string S1 is "ABC123", and the value of the string s is not changed
4.13. Converting other types of data to string types
The purpose of the ValueOf method is to convert other types of data to string types. It is important to note that there is no conversion between the base data and the string object using the syntax of the previous coercion type conversion.
Also, because the method is a static method, you do not have to create a string object. For example:
int n = 10; String s = String.valueOf(n);
The value of the string s is "10". Although there is no change for programmers, the type of data has changed for the program.
To introduce a simple application, the logical code for judging a number of natural numbers is as follows:
int n = 12345; String s = String.valueOf(n); int len = s.length();
The length of the string here, Len, represents the number of bits of the natural number. This judgment is logically simpler than the mathematical judgment method.
5. Common methods of StringBuffer and StringBuilder
In general, StringBuilder used more, here is a simple introduction of StringBuilder common methods, the two are basically the same.
5.1. Initialization of StringBuilder
StringBuilder sb=new StringBuilder();
5.2. Add element Data
There are 2 ways to add elements to StringBuilder, one at the tail, and append (), for example:
sb.append("sss"); sb.append(4); sb.append(‘3‘);
The other is to insert the specified element at the specified location, for example:
sb.insert(0, "2");
5.3. Deleting elements
Sb.delete (start, end); You can delete elements from start to position to end position, starting with 0, and the end position will also be deleted. It is important to note that start and end cannot be equal, such as Sb.delete (0, 0); If you want to delete the character at the specified position, you can use Sb.deletecharat (index) and the same index starting with 0.
5.4. Replacing elements
You can use Sb.replace (start, end, str) to replace the element from start to finish, the replacement content is STR, note that STR must be a string, and start, and end is equal, so that is the replacement character. For example:
sb.replace(0, 0, "eu");
Similar to replacing a character with a new one.
sb.setCharAt(index, char);
5.5. String inversion
Reverse () can reverse the string. The method of use is Sb.reverse ();
5.6. Find the length of the string
The length () method can be used to obtain the string lengths, using the Sb.length () method.
5.7 Get where characters and characters appear at a location
char charAt (int index); Gets the character of a position.
int indexOf (String str); Gets the position of the first occurrence of a string in the data
5.8 Getting substrings
Sb.substring (start, end), gets the substring from the start to the end, returns the string type, and returns all subsequent strings from the starting position if only the start is written. Example: Sb.substring (Start).
If you want to return a sequence, you can use Charsequence out=sb.subsequence (0, 2);
5.9 Convert to String
Sb.tostring () can be converted to a string.
Summary of String, StringBuffer, StringBuilder in Java