Java Learning: Java string processing

Source: Internet
Author: User
Section I, String objects                       A,        Java strings are processed as String objects. When you create a string object, the string that is created cannot be changed. Each time you need to change the string, create a new string object to hold the new content. The original string does not change. This method is used because the implementation of a fixed, immutable string is more efficient than implementing a mutable string. For those who want to change the string, there is a friend of the string class called StringBuffer, whose object contains the strings that can be changed after the creation.        string classes and StringBuffer classes are defined in Java.lang. So they can be automatically used by all programs. Both are described as final, which means that neither contains subclasses.   II, String constructor        (1) string (), default constructor, no parameters         STRING S1 = new string ();               (2) String (char chars[]), incoming character array                char[] mychars={' A ', ' B ', ' C '};               string s2 = new String (mychars)  //initializes s2 using the string "ABC"        (3) String (char chars[], int startIndex, int numchars), passing in an array of characters, getting the specified number of characters from the specified subscript position, Initializes the string variable with these characters.               char[] mychars={' h ', ' e ', ' l ', ' l ', ' O '};               string s3 = new String (mychars,1,3);  //uses the string "ell" to initialize S3        (4) string (string strobj), passing in another string object, which is initialized with the contents of the string object.               string s4= new String (S3);  // This is S4 is also "ell".        (5) String (byte asciichars[])                 string (byte asciichars[], int startIndex, int numchars)                Although the Java char type uses a 16 bit (bit) to represent the Unicode coded character set, in the Internet, The typical format of a string uses a 8-bit array of ASCII character sets, because the 8-bit ASCII string is common when given a byteArray, the string class provides the constructors for the above two initialization strings. Example: package examples; Class substringconv{       public static void Main (string[] args) {   & nbsp;          byte ascii[]={65,66,67,68,69,70};               string S1=new string (ASCII);               System.out.println (S1);               string S2=new string (ascii,2,3);               System.out.println (S2);       }} Compile and run output: ABCDEF CDE   III,        (1) The length () method of the calling string can be used to get the lengths of the string (number of characters);               (2) Describes how to use the new operator to create a string instance. However, this is an early approach to using string constants. For each string constant in the program, Java automatically creates a string object. Therefore, you can use string constants to initialize sTring object. For example:        String s5= "abc";        int i = "abc". Length (); You can manipulate a string as an object        (3) You can use the "+" operator to concatenate two strings to produce a new string object. As long as the + operator has one operand that is an instance of string (string), the compiler converts another operand to its string form. This is done by calling a string conversion method valueof () defined by the string class. For simple types, the valueof () method returns a string containing a string of values for that type. For objects, the valueof () method calls the ToString () method. Each class executes the ToString () method because it is defined by object. The ToString () method has the following general form: String ToString ()   . The ToString () method returns a String object (that is, a string). This object is generally a description of the class.   Four or one string operations        (1) Character interception                *char  charat (int where), note that this returns a char character for example:                Char A;               a= "ABCDE". CharAt (2);  //will index to 2, That is, the third word assignments to a               * void GetChars (int sourcestart, int sourceend, char target[], int targetstart), here is no return value method, Specifies the start and end subscript of the substring to intercept, and then specifies the array in which to store the characters within the substring, and the starting position where the characters are stored. Note that the substring does not include characters that are at the end of the subscript.                      * byte[] GetBytes ()     This is the simplest form of the getBytes () method, which implements storing characters in a byte array. GetBytes () is most useful when outputting string (string) values to an environment that does not support 16-bit Unicode encoding. For example, most Internet protocols and text file formats use 8-bit ASCII encoding for text interchange.    * Char[] tochararray ()   The simplest method of converting all characters in a string to a character array, or it can be implemented using the GetChars () method.   (2) string comparison     * Boolean equals (object str)   Compare two string objects for equality,    Boolean Equalsignorecasej (String str)   compares two string objects and ignores the case of characters    * regionmatches () method allows you to compare the interval specified in one string with the interval specified in another string, and its overloaded form allows you to ignore the case when comparing. The general form of the two methods is given below:    boolean regionmatches (int startindex,string str2,int str2startindex,int numchars) Boolean regionmatches (boolean ignoreCase, int startindex,string str2,int Str2startIndex,int numchars)      where startindex specifies the starting position of the substring of the string that calls this method. The * boolean startswith (string str)     StartsWith method also has a second form:  boolean startwith (string str, int StartIndex)    boolean endsWith (String str)       The above method is used to determine whether a given string starts or ends with a specified string. the * int compareTo (String str) method is used to compare the size of two strings. Results of string comparisons and their implications:
value meaning
less than 0 The string that calls this method is less than the argument str
greater than 0 The string that calls this method is greater than the parameter str
equals 0 two words Character string equality
  (3) Other operations * search string: int indexof (int ch) int lastindexof (int ch) int indexof (String str) Int las Tindexof (String str) Specifies the starting point of the search: int indexof (int ch, int startIndex) int lastindexof (int ch, int startIndex) int  indexof (string str, int startIndex) int lastindexof (string str, int startIndex)   * Use SUBSTRING () to intercept substrings:        string substring (int startIndex)     Note that string in substring is not capitalized, and the substring after the specified position is intercepted.        string substring (int startindex,int endindex) intercepts substrings of the specified start and end positions. Note that the intercepted character string does not include characters at the end position. The   * CONCAT () connects a string, performing the same function as the + operator.        string concat (String str)                  * REPLACE () replaces the specified character in the specified string with another character: string replace (char original, char replacement) & nbsp;   Example:        String s= "Hello". Replace (' l ', ' w ');  //after execution s= "Hewwo";                * TRIM () returns a string, The string is a string that is derived from the whitespace before and after the call string                       * Change the capitalization of characters within a string                 string tolowercase () returns a string with all lowercase letters                 string touppercase () returns a string with all uppercase letters             * Using the valueof () method to implement data conversion                For example: string str = string.valueof (3);  //converts an int type to a string type, and other basic data types and objects of any class can also be parameters.   section II, StringBuffer StringBuffer defines the following three constructors:        StringBuffer ()                  //default constructor, reserved 16 characters of space, The space does not need to be redistributed        stringbuffer (int size)  //Sets the specified buffer size stringbuffer (String str)// Sets the contents of the StringBuffer object initialization and reserves 16 character spaces without the need to allocate space * int length ()        call Length () Method can get the length of the StringBuffer object, and call capacity () to get the total allocated capacity. All two methods return a value of type int.        * void ensurecapacity (int capacity) If you want to allocate space for some characters after you construct the StringBuffer object, You can use the Ensurecapacity () method to set the size of the buffer, which is useful in cases where you know you want to append a large number of small strings to the stringbuffer. The Ensurecapcity () method has the following general form:  void ensurecapacity (int capacity) * void SetLength (int len) uses SetLength () Method can set the length of the StringBuffer object in its general form as follows: void setlength (int len)     If Len is greater than the current length of the StringBuffer object () Value, then a null character is appended to the StringBuffer object, and the string behind Len is lost if it is smaller than length ().        * Char charAt (int where)         void Setcharat (int where, char ch)    Use the Charat () method to get the character at the specified position in the StringBuffer object, Setcharat ()         you can set the characters at the specified location. Their general form is as follows:        Char charAt (int where)        void setcharat (int where,char ch)         for both of these methods, the where value must be non-negative and not exceed or equal the length of the StringBuffer object. * GetChars (int suorcestart,int Sourceend,char target[], int targetstart) * APPEND ()  append () Method connects the string form of any other type of data to the back of the calling StringBuffer object, which has an overloaded form for all built-in types and object. The following are several forms: StringBuffer append (String str) stringbuffer append (int num) stringbuffer append (Object obj)   * INSERT () &N The Bsp;insert () method inserts a string into another string. Here are some of its forms:  stringbuffer insert (int index,string str)  stringbuffer insert (int index,char ch)   StringBuffer Insert (int index,object obj)          *reverse ()              //StringBuffer reverse ()          stringbuffer strbf=new stringbuffer ("ABCDEFG");         strbf.reverse ();          system.out.println (STRBF); Output GFEDCBA           * stringbuffer Delete (int startindex,int endindex)         stringbuffer deletecharat (int loc)        Deletes the string at the specified position and the character at the specified position. For example, delete all characters after the first character:         strbf.delete (1,strbf.length ());          * replace ()              It completes the function of using a string inside StringBuffer to replace another string that specifies the starting and ending positions, noting that the substituted character does not include the character at the end position, and its general form is:          stringbuffer Replace (int startIndex, int endindex,string str)         * SUBSTRING ()   Return part value of StringBuffer         string substring (int startIndex)         string substring (int startIndex, int endindex)

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.