Overview of the String class

Source: Internet
Author: User

String class

A string is a special object that cannot be changed once it is initialized.


1) Compare the differences between the following expressions

    1. String str1 = "abc";

    2. String str2 = new String ( "abc" );

The first one creates an object reference variable STR1 to the string class in the stack, and then goes to find out if "abc" is saved in the string constant pool.

if not, create a value of three char in the stack ' A ', ' B ', ' C ' , and then creates a string object in the heap, the value of which is the array { ' A ', ' B ', ' C '}, which consists of the three char values created in the stack just now. This string object is then stored in the string constant pool, and str1 points to the address of the object.

If "abc" is already stored in the string constant pool, the object with the value "abc" is found in the string constant pool, and str1 points to the address of the object.

The first feature: the JVM will automatically determine if it is necessary to create a new object based on the actual data in the stack.

The second type can be decomposed into two steps 1, String object = "abc" ; 2, String str2 = new String (object); The first step is to refer to the first method of creation , and the second step because "ABC" has been created and saved to the string constant pool, so the JVM will only create a new string object in the heap whose value shares the three char values already in the stack.
The second feature is to create new objects in the heap, regardless of whether their string values are equal or not, and whether it is necessary to create new objects.



2) the difference between = = and equals:
Because all Java classes inherit from the object base class, and equals is implemented with = = in object, equals and = = are the same, and are all comparison object addresses, most of the classes in the Java API rewrite the Equals method, including the wrapper class for the base data type, String class, and so on. For the string class = = To compare the addresses of two string objects, equals is used to compare the contents (values) of two string objects.



3) String function Find Practice

 @Testpublic  void  test0 () {         String str =  "AFCDEABC";//1, gets the position where a letter appears. System.out.println ("IndexOf (' a ') =" +str.indexof (' a '));//0system.out.println ("LastindexOf (' a ') =" +str.lastindexof (' a ')); /5//2, gets the character on the corner label 3. System.out.println ("charAt (3) =" +str.charat (3));//3, turns the string into uppercase string s1 = str.touppercase (); System.out.println ("uppercase=" +s1);//abcdeabc//4, whether the string starts with a demo or not, ends with. java. Boolean b1 = str.endswith (". Java"); Boolean b2 = str.startswith ("Demo");//5, Whether the string contains a CD string. System.out.println ("contains (\" cd\ ") =" +str.contains ("CD");//6, intercepts the string between 2,5. SYSTEM.OUT.PRINTLN ("substring (2,5) =" +str.substring (2,5));//7, replacing A in a string with a K. SYSTEM.OUT.PRINTLN ("replace (' a ', ' k ') =" +str.replace (' a ',  ' K ') ");//8, string comparison size. System.out.println ("CompareTo (\" aaa\ ") =" +str.compareto ("AAA"));} 


Run results

indexOf (' a ') =0

lastindexOf (' a ') =5

charAt (3) =d

UPPERCASE=AFCDEABC

contains ("CD") =true

substring (2,5) =CDE

replace (' A ', ' K ') =KFCDEKBC

compareTo ("AAA") =5



4) CompareTo (String anotherstring)  
Compares two strings in a dictionary order.

    public int ( string

compares two strings in a dictionary order. The comparison is based on the Unicode values of the individual characters in the string. compares the sequence of characters represented by this string object in dictionary order with the sequence of characters represented by the parameter string. If this string object is in the dictionary order before the parameter string, the comparison result is a negative integer. If this string object is in the dictionary order after the parameter string, the comparison result is a positive integer. If the two strings are equal, the result is 0;



5) String Programming Exercise 1

indexOf (String str, int fromIndex)  
Returns the index position of the specified substring at the first occurrence of this string, starting at the specified Fromindex index.


/** * 1, gets the number of occurrences of the specified substring in a string. "Nbaernbatynbauklnba" */@Testpublic void test1 () {String str = "Nbaernbatynbauklnba"; String sub = "NBA"; int count = 0;//Count int index = 0;//define the variable record the actual position of each lookup. while ((Index=str.indexof (sub, Index))!=-1) {count++;index+=sub.length ();} System.out.println ("count=" +count);



6) String Programming Exercise 2

tri M () &NBSP,

/** * Write a method yourself to remove whitespace at both ends of the string. "AB C"--"AB C", * Achieve and trim () the same effect */@Testpublic void Test2 () {String str = "AB C"; SYSTEM.OUT.PRINTLN (Mytrim (str));} public string Mytrim (String str) {if (!str.startswith ("") &&!str.endswith ("")) {return str;} Else{int Start=0;int end = Str.length () -1;//the position of the head-to-head to determine the space, if it is to continue the loop to determine whether the next is a space while (Start<=end && Str.charat (start) = = ") {start++;} The position of the tail angle is judged by the space, if it is to continue the loop to determine whether the next is a space while (Start<=end && str.charat (end) = = ") {end--;} Return str.substring (start,end+1);//contains head without tail}}


7) String Programming Exercise 3

/** * Reverses a string. "Acqzk"--"KZQCA"; */@Testpublic void Test3 () {String str = "ACQZK"; SYSTEM.OUT.PRINTLN (Reverse1 (str)); SYSTEM.OUT.PRINTLN (Reverse2 (str));} Using Stringbufferpublic string reverse1 (String str) {StringBuffer SB = new StringBuffer (); for (int i=str.length () -1;i> -1;i--) {sb.append (Str.charat (i));} return sb.tostring ();} Take advantage of the number private string Reverse2 (String str) {char[] ch = str.tochararray (); for (int start=0,end=ch.length-1;start<end; start++,end--) {Char temp = Ch[start]; Ch[start] = ch[end];ch[end] = temp;} return new String (CH);}






Overview of the String class

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.