Java string processing, java string

Source: Internet
Author: User
Tags textout

Java string processing, java string

I. Overview

Java is implemented as a String type object. String is a class. After a String object is created, the created String cannot be changed. When you need to use modifiable strings, Java provides two options: StringBuffer and StringBuilder. Note: variables declared as String references can be changed at any time to point to some other String objects.

Ii. String Constructor

The difference between String s1 = "hello" and String s2 = new String ("hello:

The String class manages a String constant pool (a part of the constant pool) in the memory. All the same String constants in the pool are merged, occupying only one space.

String s1 = "hello". check whether there is any hello in the pool. If no hello is found, create a hello String object. This method is used to create 0 or 1 objects.

String s2 = new String ("hello"). Here, a hello object is created in the pool, which is the same as s1. When new String () is created, the hello object is copied to heap, s2 points to hello in the heap. This method is used to create one or two objects (an object is created when there is hello in the pool ).

The memory diagram is as follows:

Iii. Method functions of the String class

There are many methods for the String class. Here we only introduce several common functions:

1. String Length:

Int length ();

2. String Conversion

Each class implements the toString method because it is defined by Obect. For most self-created classes, you usually need to override toString () and provide your own string expression.

Eg:

 1 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     public String toString()11     {12         return "test_x"+"-----"+x+"\n"+"test_y"+"-----"+y;13     }14 }15 public class Tset16 {17     public static void main(String[] args)18     {19             Box b=new Box(1,3);20             System.out.println(b);21     }22 23 }

The result is as follows:

Q: I have read the source code of println. I don't know why the output is so?

 1 private void write(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();10             }11         }12         catch (InterruptedIOException x) {13             Thread.currentThread().interrupt();14         }15         catch (IOException x) {16             trouble = true;17         }18     }

3. character extraction

CharAt (): returns the char value at the specified index. GetChars (): extract multiple characters at a time. GetBytes (): stores characters in byte arrays.

4. String comparison

The equals () and =: equals () Methods Compare the characters in the String object, and the "=" operator compares whether two objects reference the same instance.

Eg:

1 public class Test 2 {3 public static void main (String [] args) 4 {5 String s1 = new String ("hello"); // create two objects, A pool and a heap with 6 String s2 = "hello"; // create an object. s2 points to "hello" Object 7 String s3 = "hello" in the pool "; // create 0 objects, pointing to s2 pointing to the object in the pool 8 String s4 = s2; // create 0 objects, pointing to s2, s3 points to the object 9 String s5 = new String ("hello") in the pool; // creates an object in the heap. Note that it has nothing to do with s1 10 11 System. out. println (s2 = "hello"); // true 12 System. out. println (s2 = s3); // true, because it points to the "hello" 13 System in the pool. out. println (s2 = s4); // true, same as above, so s3 and s4... :) 14 System. out. println (s1 = s5); // false, obviously, false 15 System. out. println (s1 = s2); // false, pointing to different objects 16 System. out. println (s1 = "hello"); // false17 System. out. println ("---------------"); 18 s1 = s2; 19 System. out. println (s1 = "hello"); // true20} 21}

Execution result:

Boolean startsWith (String prefix): determines whether a given String starts with a specific String. Boolean startsWith (String prefix, int toffset): determines whether the String starting from the specified index starts with the specified prefix. EndsWith (): determines whether a given String ends with a specific String. CompareTo (): used to compare the string size and consider uppercase and lowercase letters. CompareIgnoreCase (): Compares the string size and ignores uppercase and lowercase letters.

5. Search for strings

IsdexOf (): locate the first occurrence location of a character or substring lastIndexOf (): locate the last occurrence location of a character or substring

6. Change the string

Because the String object cannot be changed, when you need to change a String, you must copy it to a StringBuffered. The latter uses the following methods, after modification, a new string copy is constructed.

Substring (int startIndex): returns a copy of The substring (int startIndex, int endIndex) from startIndex to the end of the call String, specifying the start and end points, and returns the string in the middle, the endpoint is not included. Concat (): connects two strings, which are the same as the "+" operator. Replace (char originial, char replacement): replace it with one character in all the places where another character appears in the call string. Replace (CharSequence originial, CharSequence replacement): replace another string sequence with one string sequence. Trim (): returns a copy of the call String object, but all the leading and trailing spaces are deleted (the trailing spaces are not deleted ).

7. Change the case sensitivity of Characters in the string.

ToLowerCase (): change all characters to lowercase toUpperCase (): change all characters to uppercase

Iv. StringBuffer class

StringBuffer is a peer class of String. It provides many functions of String, which can be increased and rewritten.

Here we only introduce several StringBuffer class method functions:

1. append (): concatenates a string of any data type to the end of the called StringBuffer object.

When a String object uses the "+" operator, the append method is often called.

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 (): reversing the characters in the StringBuffer object

4. delete (int startIndex, int endIndex) and delete (int loc): delete a string of characters in the called object.

V. StringBuilder class

In addition to an important difference, it is equivalent to StringBuffer. This difference is that it is not synchronous, meaning it is NOT thread-safe, and its advantage is faster performance, stringBuffer must be used when multithreading is used.

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.