Java string processing

Source: Internet
Author: User

I. Overview

Java is a string-type object that implements strings. String is a class that cannot be changed when a string object is created. Java provides two choices for-stringbuffer and StringBuilder when you need to use a modifiable string. Note: Variables that are declared as string references can be changed at any time to point to some other string object.

Two, string constructors

String s1= The difference between "Hello" and string s2=new string ("Hello"):

The string class manages a string Chang (part of a constant pool) in memory, and all the same string constants in the pool are merged, occupying only one space.

String s1= "Hello", first see if there is no hello in the pool, do not create a Hello string object. This method is used to create 0 or 1 objects.

String S2=new string ("Hello"), where you first create a Hello object in the pool, with S1, and then New String (), copy the Hello object into the heap heap, S2 point to Hello in the heap. When you use this method, create 1 or 2 objects (an object is created when there is a hello in the pool).

The memory graph is as follows:

Third, method functions of the String class

There are many methods of the string class, and here are just a few common functions:

1, the length of the string:

int length ();

2. String conversion

Each class implements the ToString method, because it is defined by Obect, and for most self-created classes, it is common to override ToString () and provide its own string expression.

eg

1 classBox2 {3     intx;4     inty;5Box (intXinty)6     {7          This. x=x;8          This. y=y;9     }Ten      PublicString toString () One     { A         return"Test_x" + "-----" +x+ "\ n" + "test_y" + "-----" +y; -     } - } the  Public classTset - { -      Public Static voidMain (string[] args) -     { +Box b=NewBox (1,3); - System.out.println (b); +     } A  at}

The results shown are:

Question: Look at the source of println, do not know the output here is why this?

1 Private voidWrite (String s) {2         Try {3             synchronized( This) {4 Ensureopen ();5 Textout.write (s);6 Textout.flushbuffer ();7 Charout.flushbuffer ();8                 if(AutoFlush && (s.indexof (' \ n ') >= 0))9 Out.flush ();Ten             } One         } A         Catch(Interruptedioexception x) { - Thread.CurrentThread (). interrupt (); -         } the         Catch(IOException x) { -Trouble =true; -         } -}

3. Character extraction

CharAt ():  char  value. GetChars (): Extracts more than one character at a time. GetBytes (): Stores characters in a byte array. 

4. String comparison

The Equals () and ==:equals () methods compare the characters in a string object, and the "= =" operator compares whether two objects refer to the same instance.

eg

1  Public classTest2 {3      Public Static voidMain (string[] args)4     {5String s1=NewString ("Hello");//Create 2 objects, one pool and one heap inside6String s2= "Hello";//Create 1 objects, S2 point to the "Hello" object inside the pool7String s3= "Hello";//Create 0 objects, point to the object that S2 points to in the pool8String s4=s2;//Create 0 objects, point to the object that S2,s3 points to in the pool9String s5=NewString ("Hello");//Create 1 objects inside the heap, note that it's okay with S1Ten  OneSystem.out.println (s2== "Hello");//true ASystem.out.println (S2==S3);//true, because it points to the "hello" in the pool. -System.out.println (S2==S4);//true, ditto, then S3 and S4 ...:) -System.out.println (S1==S5);//false, it is obvious that false theSystem.out.println (S1==S2);//false, pointing to an object that is not the same -System.out.println (s1== "Hello");//false -System.out.println ("---------------");  -s1=S2; +System.out.println (s1== "Hello");//true -     } +}

Execution Result:

Boolean startsWith (string prefix): Determines whether a given string starts with a specific character.  boolean startsWith (string prefix,int  toffset): Determines whether the string starting at the specified index begins with the specified prefix. EndsWith (): Determines whether the given string ends with a specific string. CompareTo (): Used to compare string sizes and to consider uppercase and lowercase letters. Compareignorecase (): Compares the string size and ignores uppercase and lowercase letters. 

5. Find string

Isdexof (): Finds the first occurrence of a character or substring LastIndexOf (): Finds the last occurrence of a character or substring

6. Change the string

Because the string object cannot be changed, when a string needs to be changed, it must be copied to a stringbuffered, which uses the following method, which constructs a new copy of the string after the change.

SUBSTRING (int  startIndex): Returns a copy of the substring starting from StartIndex to the end of the calling string substring (int StartIndex, int EndIndex), specifying the start and end points, returns the middle string, excluding the end point. Concat (): Connects two strings,the same as the "+" operator. Replace (char originial,char  replacement): Replace with one character where all occurrences of another character in the calling string occur. Replace (charsequence originial,charsequence replacement): Replaces another string sequence with a sequence of strings. Trim (): Returns a copy of the calling string object, but all the beginning and end whitespace characters are deleted (whitespace characters in the middle of the character are not deleted). 

7. Change the case of characters in a string

toLowerCase (): Change all characters to lowercase touppercase (): Change all characters to uppercase

Four: StringBuffer class

StringBuffer is a peer class of string that provides many of the functions of a string that can grow and be rewritten.

Here are just a few of the method functions of the StringBuffer class:

1, append (): Connects the string representation of any data type to the end of the called StringBuffer object.

The Append method is often called when a string object is used with the "+" operator.

StringBuffer s=New stringbuffer ("Hello");    System.out.print (S.append ("World"));

2, inser (int index,string str): Inserts a string into another string.

3. Reverse (): Reverses the characters in the StringBuffer object

4, delete (int startindex,int endIndex), delete (int loc): Removes a string of characters from the calling object.

Five, StringBuilder class

In addition to an important distinction, the difference is that he is not synchronous, meaning that he is not thread-safe, that the advantage is faster performance, and that it must use StringBuffer when using multi-threading, StringBuffer.

Java string processing

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.