Java string, string buffer __java base

Source: Internet
Author: User

This article studies and summarizes the strings in Java. Content includes string string common method, stringbuffered and StringBuilder function Introduction, learn to practice some questions in the forum, but also to the knowledge of the verification of the consolidation.

String class

String is a Java string class that is final decorated and cannot be inherited, and all string literals in the Java program, such as "ABC", are implemented as instances of this class.
In Java, strings are constants that cannot be changed once initialized, and any change to a string object returns a new string object.

string constant Pool

The constant pool, each class has a corresponding constant pool, Chang (constant pool) refers to some data that is determined at compile time and is saved in the compiled. class file. It includes constants in classes, methods, interfaces, and so on, and the string constant pool is part of a constant pool.
Before the JVM started, the string constant pool information for a class had been identified, written in the. class file, and after the JVM was started, the string constant pool was loaded into the in-memory method area.
In a string constant pool, each string constant is unique and has no more than one copy of the same literal value.
The string constant pool is maintained privately by the string class.
When the program is running, you can dynamically expand the string constant pool by using the Intern () method of the String class. When the Intern method is invoked, the string in the pool is returned if the pool already contains a string that is equal to this string object (determined by the Equals method). Otherwise, this string object is added to the pool and a reference to this string object is returned. All literal strings and string assignment constant expressions are manipulated using the Intern method.

public class StringDemo1 {public
	static void Main (string[] args) {
		string s1= ' abc ';//Create a String reference variable S1, Point to the "ABC" string in the string constant pool. String
		s2=new string ("abc"); The S2 reference variable is created in the stack memory, the "ABC" string object is created in the heap, and is S2 pointed to.
		String s3= "a" + "BC";//"A" and "BC" are synthesized as string constants "ABC", first find out if there is an "ABC" string object in the string constant pool, there is no longer recreating the object, S3 and S1 point to the same object in the string constant pool, S1 ==s3.
		String s4= "A" +new string ("BC");//The "BC" object is created in the heap, added to "a", and the new string object is assigned to S4,S4 also points to a string object in the heap.
		System.out.println (S1==S2);//false
		System.out.println (S1==S3);//true
		System.out.println (S1==S4);//false
		System.out.println (S2==S4); False
		System.out.println (s1.equals (S2));//true
		System.out.println ("=============================");
		String S5=new string ("Def");//The actual creation of 2 objects, "Def" in the string constant pool after compilation completes, and the runtime creates a String class object "Def" in heap memory.
		String s6= "def";
		System.out.println (S5==S6);//false S5 Point to the "Def" object in heap memory, S6 is a "def" string object in the string constant pool.
		System.out.println (S6==s5.intern ());//true, S5.intern () points to the "Def" string object in the string constant pool.		
	}
}

string Common operations
1. Obtain
1 Gets the length of the string: int length ()
2 to obtain the character at the position according to the position:
char charAt (int index), stringindexoutofboundsexception exception occurs when index crosses the line.
3 Gets the position of the character (substring) in the string based on the character (substring):
int index (int ch), which is the ASCII code of the character, returns the first occurrence of the CH in the string, and returns 1 when there is no ch in the string;
int index (int ch,int fromindex), start search from fromindex position, no time return-1;
int index (string str), gets the position where the string str first appears in another string, and returns-1 when not;
int lastindex (int ch), reverse lookup, returns the position of Ch last seen.
2. Judge
1 Whether a string contains a substring:
Boolean contains (String str), which can actually be implemented through the index (string str) method;
2 whether the string begins with the specified content: Boolean startwith (String str);
3 whether the string ends with the specified content: Boolean endwith (String str);
The above 3 methods can be combined to achieve a common file name search.
4 whether the string has content: Boolean IsEmpty (), jdk1.6 version started, the principle of this method is to determine whether the string length is 0;
5 determine whether the string content is the same: Boolean equals (String str);
6 to determine whether the content of the string is rich, ignoring case: Boolean equalsignorecase (String str);
3. Conversion
1 converts a character array into a string
You can use the String class constructor: String (char[]), string (Char[],offset,count);
You can also use the static method of the String class: Copyvalueof static string (char[])
Static String copyvalueof (Char[],offset,count)
Static String valueof (char[])
2 converting the string to a character array: char[] ToCharArray ()
3 The byte array into a string: the same as the character array to the string is basically the same, the char[] replaced by byte[] can
4 Converting a string to an array of bytes: byte[] getbytes[]
string and byte array conversions, you can specify the encoding table, which is interspersed with the knowledge of encoding and decoding.
Encoding: The string becomes an array of bytes. Decoding: A byte array becomes a string.
Several common character sets
The ASCII character set, which is represented in 1 bytes, the 1th digit is 0, and the remaining 7 digits represent a total of 127 characters, which obviously does not satisfy many languages outside of English;
ISO8859-1 encoding, European coding table, single-byte encoding, ISO 8859-1 compliant ASCII, in the 0xa0-0xff of the ASCII-code vacancy, added 96 letters and symbols for use in the Latin alphabet using the diacritics, ISO 8859-1 also known as Latin-1;
gb2312/gbk/gbk18030, the GB code of Chinese characters, is expressed as a Chinese character in 2 bytes. GB2312 is only used to express simplified characters, contains more than 6,000 Chinese characters, GBK completely reverse compatible GB2312 encoding, GBK encoding can be used to express both traditional and simplified characters, contains more than 20,000 Chinese characters, GBK can also encode English letters, English alphabet encoding compatible ISO8859-1 encoding ( The English alphabet is expressed in a single byte. GBK later expanded into GBK18030.
Unicode, International code value, all characters used fixed-length double byte representation (fixed-length coded computer processing convenient), can be used to represent all language characters, including English letters; Unicode is incompatible with any encoding, but, relative to iso8859-1 encoding, The Uniocode code only adds a 0 byte to the front, such as the letter ' a ' to ' 00 61 '.
UTF-8, International code value, can be used to represent the characters in all languages; variable length byte encoding, each character length from 1-3 bytes, can be loaded in one byte with a byte, and so on. Generally speaking, English letters are expressed in a byte, compatible with Iso8859-1, and Chinese characters use three bytes, the same Chinese characters in UTF-8 and GBK encoding may not be the same.

Import java.io.UnsupportedEncodingException;
Import Java.util.Arrays;
		public class Encodedemo {public static void main (string[] args) throws unsupportedencodingexception {String a= "Hello"; Byte[] B1=a.getbytes ("GBK");
		The encoding default character set is GBK, so it is not written.
		System.out.println (Arrays.tostring (B1));
		String S1=new string (B1, "GBK");/the decoding default character set is also "GBK", where "GBK" can not be written.
		
		System.out.println (S1); Byte[] B2=a.getbytes ("UTF-8");
		Use the UTF-8 character set encoding System.out.println (Arrays.tostring (B2));//b1 length is 3 bytes of a Chinese character in 6,utf-8.		
		
		String S2=new string (B2, "GBK"),//utf-8 encoded byte array, GBK decoding, every 2 bytes to match GBK decoding table, garbled System.out.println (S2); Byte[] B3=a.getbytes ("iso8895-1");
		
		Run Post exception java.io.UnsupportedEncodingException because the iso8859-1 character set does not recognize the text, can not be encoding; Once the string encoding fails, it can no longer decode successfully.
		Byte[] B4=a.getbytes ("GBK");
		System.out.println (arrays.tostring (B4))//b1 length is 3 bytes of a Chinese character in 6,utf-8.
		String S4=new string (B4, "iso8859-1"),//encoded successfully, but decoding error, can be remedied, will b4 first with iso8895-1 decoding, and then with GBK decoding.
		System.out.println (S4);
		Byte[] B5=s4.getbytes ("iso8859-1"); System.Out.println (Arrays.tostring (B5));
		String S5=new string (B5, "GBK");
	System.out.println (S5);
The results of the run: [-60,-29,-70,-61] Hello [-28,-67,-96,-27,-91,-67] Raccoon 犲 ソ[-60, -29, -70, -61]???? [-60,-29,-70,-61] Hello
5 Converts the base data type to a string: static string valueof (Int/byte/double, etc.).

4. Replace
String Replace (Oldchar,newchar), string replace (OLDSTR,NEWSTR), if the character or string to be replaced does not exist, returns the original string.
5. Cutting
String[] Split (String regex);
Note that if you use the "." and "|" The cut string, because these 2 are all escape characters, must be added "\", that is, Str.split ("\.") and Str.split ("\\|").
6. Get substring
1) string subString (Begin,end), the returned substring has a begin, but does not contain end, including the head does not contain tail;
2) String subString (begin), equivalent to subString (Begin, Str.length ()).
7. Remove space, compare
1) to convert the string to uppercase or lowercase: string toUpperCase (), String toLowerCase ()
2 Remove multiple spaces at both ends of the string: string Trim ()
3 A natural order comparison of 2 strings:
int CompareTo (str), returns 0 when equal, otherwise returns the difference of the ASCII value of the 1th unequal character in 2 strings.
The following are 2 exercises related to the string class, and the topic itself solves a more meaningful problem, put it here for a record:

/* Problem: Enter a string without repeating characters, outputting the entire arrangement of these characters.
* * * thinking: basically is in accordance with the principle of the arrangement of mathematics, the arrangement of multiple characters, can be recursively divided into the first character and the remaining characters to form the whole arrangement of the word subcode string combination.
* * Import java.lang.*;
Import java.util.*;
       Class quanpl{public static void Main (string[] args) {String str= "abc";
       System.out.println ((Allmaxlen (str)). Size ());
       SYSTEM.OUT.PRINTLN (Allmaxlen (str));
    SYSTEM.OUT.PRINTLN (All (str)); }//String all arranged, length from 1 to str.length () public static arraylist<string> all (String str) {arraylist<string> A
    	L=new arraylist<string> ();
    		if (Str.length () ==1) {al.add (str);
    	Return al;
    			}else{String Sa=str.charat (0) + "";
    			Al.add (SA);
    			String sub=str.replace (SA, "");
    			Recursive arraylist<string> Tk=all (sub) of substrings;
    			Al.addall (TK);
    			Iterator<string> It=tk.iterator ();
    			String S=null;
    				while (It.hasnext ()) {s=it.next (); for (int j=0;j<=s.length (); j + +) {//traversing the position of the SA when it was added to S Al.add (s.substring 0,j) +sa+s.substring (J,s.length ());
    }} return Al;
    The string in the//length Str.length () is in full order. public static arraylist<string> Allmaxlen (String str) {arraylist<string> al=new Arraylist<string&gt
        ;();
            if (Str.length () ==1) {al.add (str);            
        Return al;
            }else{char[] Ch=str.tochararray ();
                for (int i=0;i<ch.length;i++) {////To traverse String sub=str.replace (ch[i]+ "", "" ") for the desirable characters on the 1th position; ArrayList Arr=allmaxlen (sub);
                Recursion is arranged to remove the remaining substring of the character on the 1th position//system.out.println (arr);
                Iterator<string> It=arr.iterator ();
                    while (It.hasnext ()) {string s=new string ();
                    String Ss=it.next ();
                String Re=ch[i]+it.next (); The whole string is the Al.add (re);            
        } return to Al;
 }        
    }
}
/* Look for the same maximum substring in 2 strings, and if there are 2 or more different maximum identical substrings, put them all back in a ArrayList object.
* * Import java.util.*; 
         Class test5{public static void Main (string[] args) {String s1= "Kiokk";
         String s2= "Kib3oktr";
System.out.println (maxsubstring (S1,S2));
                public static ArrayList maxsubstring (string s1,string s2) {string max,min; int len=0; The length used to hold the maximum substring arraylist<string> al=new arraylist<string> (); Used to store the maximum substring max= (s1.length () >s2.length ())?
                S1:S2; Min= (MAX==S1)?
                S2:S1;
                System.out.println (max+ "..." +min);
                                for (int x=0;x<min.length (), x + +) {for (int y=0,z=min.length ()-x;z!=min.length () +1;y++,z++) {
                                String temp=min.substring (y,z);
                                Temp.tochararray ();
                                 String[] Q=null;
     System.out.println ("temp=" +temp);                           if (Max.contains (temp)) {//syst
                                EM.OUT.PRINTLN ("The result is" +temp); if (Temp.length () >=len) {//code first produces the same substring of the length is certainly the largest, so the judge is no problem, followed by the same length of the substring also added to the Al Len=temp.                                
                                Length ();
                                Al.add (temp);
                }
                                }                                                      
                }
Return to Al; }//Run results will ok,kk output.
StringBuffer class

The string buffer, which is a container, the final class, cannot be inherited.
features : Length can be changed, can directly manipulate multiple data types, and eventually through the ToString () method into a string.

The

StringBuffer, as a container, can be used for additional pruning and checking operations.
1. Store
StringBuffer append (), parameters can be string objects, StringBuffer objects, 6 basic data types (except byte and short), character array ( Offset and count can be specified, and the specified parameter is added to the end of existing data, returning the original object.
StringBuffer Insert (index, data) inserts data into the specified index position, and the index exceeds the current maximum position of the string, and there is a corner-crossing exception.
2. Delete
StringBuffer Delete (start,end), delete data in buffer, include header without tail
StringBuffer Delete (charAt (index) Deletes the character
Strubgbuffer Delete (0,sb.length ()) at the specified location, emptying the buffer
3. Get
Char charAt (int index)
int indexOf (string str)
int lastindexof (string str)
int length ()
String subString (int start,int end)
4. Modify
void Setcharat (int index,char c)
StringBuffer replace (start,end,string str)
5. Reverse
StringBuffer reverse ()
6. GetChars () method
void getChars (int srcbegin,int Srcend,char[] Det,int Detbegin), which stores the specified data in the buffer to the destination character array.
An ingenious example of the StringBuffer application:

/* Problem: ABCD...S A total of 19 letters of the sequence of repeated stitching 106 times, to get a length of 2014 string.
    Next, delete the 1th letter (that is, the beginning of the letter a), and the 3rd, 5th, and all odd-numbered positions. The resulting new string is then removed to remove odd-position letters from the action.
 So go on, there is only one letter left, please write the letter.  */public class Stringbufferdemo {public static void main (string[] args) {String str
                 = "ABCDEFGHIJKLMNOPQRS";
                 String Ss=new string ();
                 Stitch the String 106 times for (int i = 0; i < i++) {ss=ss+str;
         } System.out.println (remove (ss));
        	 public static string Remove (String str) {StringBuffer strbu=new stringbuffer (str); while (1!= strbu.length ())///Last letter left, the Loop end condition is the last length 1 {for (int i = 0; i < Strbu.le Ngth ();
                              i++) {/* If you think of a string as an array of characters, then, by the title of the topic, you delete all the lower-numbered letters in the array, including 0.
                * But when I delete the letter at the current I, the letter behind will move one character forward, so that the next letter of the currently deleted letter has actually moved to I, and I have already increased by 1.              * So I just happens to be the index of the next letter, which is the next even digit position.  * * Strbu.deletecharat (i);   Delete the letter at index i} return strbu.tostring ();
 The final result is q}}

Stringbuild class

StringBuffer is a simple replacement of the jdk1.5 version.

Different from the StringBuffer:
StringBuffer is synchronous, thread-safe, but it is less efficient to judge the lock every time it is operated
StringBuilder are threads that are not synchronized and can be manually synchronized without the need to judge locks, high efficiency, and high thread security requirements.
Development recommends the use of StringBuilder.



 

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.