6) String class in Java

Source: Internet
Author: User
Tags first string




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 language";
In fact, according to the standard object-oriented syntax, its format should be:
string s = new String ("abc");
s = new String ("Java language");
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.

2) Common operations for strings

A) Charat method
The function of this method is to follow the index value (specifythe index value of the first character in a string is 0, the index value of the second character is 1, and so on, to obtain the specified character in the string. For example:
String s = "abc";
char C = s.chatat (1);
The value of the variable c is ' B '. b) CompareTo method
The function of this method is to compare the size of two strings, and the comparison principle is to compare 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.
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.
C) Concat method
The function of this method is to concatenate strings and concatenate 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 from left to right,if the contents of both sides of the connection are basic numeric types then the addition operation, if one of the content participating in the connection is a string, is concatenated 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.

d) EndsWith method

The function of this method is to determine whether a string ends with a string, or true if it ends with a corresponding string.
For example:
String s = "Student.doc";
Boolean B = S.endswith ("Doc");
Then the value of variable B is true.
e) Equals method
The purpose of this method is to determine whether the contents of two string objects 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, the function of this method is to ignore the case to compare whether the contents of the two strings are the same. For example:
String s = "abc";
String S1 = "ABC";
Boolean B = S. Equalsignorecase (S1);
Then the value of variable B is true.
f) GetBytes method
The function of this method is to convert the string into the corresponding byte array, so as to facilitate the storage and transmission of the data. For example:
String s = "Computer";
Byte[] B = s.getbytes (); Convert to a byte array using native default strings
Byte[] B = s.getbytes ("gb2312"); Converting to a byte array using the GB2312 character set
In the actual conversion, be sure to pay attention to the character set problem, or the Chinese will be in the conversion of problems.
g) IndexOf method
The function of this method is to find the starting position of a particular character or string in the current string (array subscript), 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.
h) 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 language";
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.
i) Replace method
The function of this method is to replace all the specified characters in the string and then generate 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 strings "BA" in string s with "12", generating a new string "a12t12c", and  the contents of the string s are not changed.
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.
j) Split method
The function of this method is to split the contents of the current string with a specific string as an interval, and a string array will be obtained after the general split. 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.

k) StartsWith methodThe method is similar to the EndsWith method, except that the method is to determine whether a string starts with a string. For example:

String s = "Testgame";
Boolean B = S.startswith ("Test");
Then the value of variable B is true.
l) Substring method
The function of this 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:
String s = "substring example";
int len = S.length (); Get string length
for (int begin = 0;begin < len–1;begin++) {//Start index value
for (int end = begin + 1;end <= len;end++) {//End index value
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.
m) ToCharArray method
The 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 '}.
N) toLowerCase method
The function of this 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.
o) Trim method
The function of this method is to remove all whitespace from the beginning and end of the string, and then form a new string. This method does not remove the space in the middle of the string. For example:
String s = "ABC abc 123";
String S1 = S.trim ();
The value of the string S1 is: "ABC abc 123". The value of the string s does not change.
p) valueof method
The purpose of this 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.
The use of the string class introduces so much, the other methods and the detailed declaration of the method here can be see the corresponding API documentation.




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.