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

Class Box  2 {3     int x; 4     int y; 5     Box (int x,int y) 6     {7         this.x=x; 8         this.y=y; 9     }10     p Ublic String toString () one     {         test_x "+"-----"+x+" \ n "+" test_y "+"-----"+y;13     }14}15 Public Class Tset16 {public     static void Main (string[] args)     {             b=new box (1,3);             System.out.println (b);     }22 23}

The results shown are:

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

private void Write (String s) {2         try {3             synchronized (this) {4                 ensureopen (); 5                 Textout.write (s); 6                 t Extout.flushbuffer (); 7                 Charout.flushbuffer (); 8                 if (AutoFlush && (s.indexof (' \ n ') >= 0)) 9                     Out.flush ();             }11         }12         catch (Interruptedioexception x) {             thread.currentthread (). interrupt ();         }15         catch (IOException x) {             trouble = true;17         }18     }

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

public class Test 2 {3 public     static void Main (string[] args) 4     {5         string s1=new string ("Hello");//create 2 objects, one Pool and a heap inside  6         string s2= "Hello";//create 1 objects, S2 point to the "Hello" object in the pool  7         String s3= "Hello";//Create 0 objects, Point S2 to the object in the pool.  8         String s4=s2;//creates 0 objects, pointing s2,s3 to the object in the pool  9         string s5=new string ("Hello"); /create 1 objects inside the heap, note that it doesn't matter with S1         System.out.println (s2== "Hello");//true         System.out.println (S2==S3);//true , because the point is the "Hello" in the pool         System.out.println (S2==S4),//true, ditto, then S3 and S4 ...:)         System.out.println (S1==S5);//false, obviously, false         System.out.println (S1==S2);//false, pointing to a different object 16         System.out.println (s1== "Hello");//false17         System.out.println ("---------------");         s1=s2         System.out.println (s1== "Hello");//true20     }21}


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.

SubstringintStartIndex): Returns a copy of the substring starting from StartIndex to the end of the calling string substring (intStartIndex,intEndIndex), specifying the start and end points, returns the middle string, excluding the end point. Concat (): Connect two strings, with "+operator is the same. Replace (CharOriginial,Charreplacement): Replace with one character where all occurrences of another character are in the calling string. 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.