Dark Horse programmer-String, StringBuffer, and basic data packaging class, stringstringbuffer

Source: Internet
Author: User
Tags string methods

Dark Horse programmer-String, StringBuffer, and basic data packaging class, stringstringbuffer

Class String------------------------------------------------

I. Overview

(1) Definition: String is a String class type used to describe String objects.

(2) features: Once a String object is initialized, it will not be changed. The String class cannot have child classes.

(3) Writing

1. Sting s = new String ("abc ");

2. String s = "abc ";

(4) Details

String s = "abc"; // create a String object in the constant pool.

String s1 = new String ("abc"); // create two objects. One is new and the other is in heap memory.

System. out. println (s = s1); // false

System. out. println (s. equals (s1 ));

// The equals in the string class rewrites the equals in the Object to establish the basis for the string class to determine whether the string Object is the same.

// Compare the string content.

Ii. common string Methods

(1) Obtain

* Int length (): gets the length of a string.

* Char charAt (int index): returns the char value at the specified index.

* Int indexOf (int ch): // return the location where ch first appears in the string.

* Int indexOf (int ch, int fromIndex): obtains the position where ch appears for the first time in the string starting from the position specified by fromIndex.

* Int indexOf (String str): // returns the position where the specified String str appears for the first time in this String.

* Int indexOf (String str, int fromIndex): obtains the position where the specified String 'str' appears in the String starting from the position specified by fromIndex.

* Int lastIndexOf (int ch): // returns the index at the last occurrence of the specified character in this string, that is, the reverse index.

(2) Judgment

* Boolean contains (str): determines whether the string contains the str substring.

Special: indexOf (str) can be used to index the position where the first str appears. If-1 is returned, the str does not exist in the string. Therefore, it can also be used to determine whether to include the specified content.

Example: if (str. indexOf ("aa ")! =-1) and this method can be used to determine and obtain the location where it appears. If it is only for judgment, use contains.

* Boolean isEmpty (): determines whether the string is null (supported by JDK1.6 ).

* Boolean startsWith (String prefix): determines whether the String starts with the specified content.

* Boolean endsWith (String suffix): whether the String ends with the specified content.

* Boolean equals (str): determines whether the content of a string is the same. it overwrites the Object class method.

* Boolean condition signorecase (): case-insensitive comparison is ignored.

(3) Conversion

* Char [] toCharArray (): converts a string into a character array.

* Convert the character array to a string:

-Constructor: String (char []);

String (char [], offset, count); // convert a part of the character array into a String.

-Static method:

Static String copyValueOf (char []);

StaticString copyValueOf (char [] data, int offset, int count );

Static String valueOf (char []);

* Convert a byte array to a string:

String (byte []);

String (byte [], offset, count); // convert a part of the byte array into a String. Count indicates the number.

* Byte [] getBytes (): converts a string to a byte array.

* Convert "Basic Data Type" to "string ":

Static String valueOf (int );

Static String valueOf (double );

Special: encoding tables can be specified during conversion of strings and byte arrays.

* String concat (String str): concatenates a String.

(4) Replacement

* String replace (oldchar, newchar): generates a new String. If the character to be replaced does not exist, the original String is returned.

* String replace (CharSequence target, CharSequence replcement): for example, str. replace ("abc", "qqq ");

(5) Cutting

* String [] split (regex): the String is cut according to the requirements of the regular expression regex, and a String array is returned.

(6) substring (obtain part of the string)

* String subString (int beginIndex): captures the subString from the inindex badge to the end of the String.

* String substring (int beginIndex, int endIndex): From the inindex badge String to the endIndex-1 badge String.

(7) convert, remove spaces, and compare

* Convert the String to uppercase or lowercase: StringtoUpperCase (), String toLowerCase ()

* Remove multiple spaces at both ends of the String: String trim ()

* Comparison of two strings in natural order: int compareTo (String str );


StringBuffer class------------------------------------------------

I. Overview

StringBuffer is a String buffer similar to a String and can be considered as a container. StringBuffer can add, delete, modify, and query string content.

Ii. Features

1. The length is changeable. (Arrays are fixed)

2. You can directly operate on multiple data types. (Only one operation can be performed on arrays)

3. The toString () method is used to convert the string.

3. Create an object

StringBuffer sb = new StringBuffer (); // The initial capacity is 16 characters.

Iv. Common Operations

  (1) Storage

StringBuffer append (): add the specified data as a parameter to the end of the existing data.

StringBuffer insert (int offset, data): You can insert data to the specified offset position.

(2) Delete

StringBuffere delete (start, end): delete data in the buffer, including start, not end.

StringBuffer deleteCharAt (index): delete a character at a specified position.

Clear the buffer: object. delete (0, object. length ());

  (3) Obtaining

Char charAt (int index );

Int indexOf (String str );

Int lastIndexOf (String str );

Int length ();

String substring (int start, int end );

  (4) Modification

StringBuffer replace (int start, int end, String str );

Void setCharAt (int index, char ch );

(5) reverse

StringBuffer reverse ();

  (6) store the specified data in the buffer to the specified character array.

Void getChars (int srcBegin, int srcEnd, char [] dst, int dstBegin)

V. JDK1.5New Features

1. In JDK1.5 and later versions, StringBuilder emerged to improve the buffer efficiency. StringBuffer is thread-synchronized and used for multithreading. StringBuilder does not synchronize threads. It is applied to a single thread and improves the efficiency.

2. Reasons for Java upgrade: (1) improve efficiency. (2) Simplified writing. (3) improve security.


Basic data type packaging-------------------------------------

The advantage of encapsulating basic data types into objects is that more function methods can be defined in objects to operate on the data. The most common function of the basic data type object packaging class is to convert between the basic data type and the string type.

I. Basic data type-Packaging

Basic Data Type

Corresponding packaging class
































Ii. "Basic Data Type"-"string"

1. Basic data type + "";

2. Basic data type. toString (Basic Data Type value ). For example, Integer. toString (25); // convert the 25 Integer to "25 ".

3. "string"-"basic data type"

1. Regular format: basic data type packaging class. parse basic type (string );

2. Code Format: xxx a = Xxx. parseXxx (string); // a string of the corresponding type must be input.

3. Example:

Int a = Integer. parseInt ("123"); // static conversion method

Integer I = new Integer ("123 ");

Int num = I. intValue (); // same as the above static method, but this is an object call method.

Boolean B = Boolean. parseBoolean ("true ");

Note: during use, Integer x = null; the above Code will show NullPointerException, which must be judged.

4. "decimal"-"Other hexadecimal"

ToBinaryString ();

ToHexString ();

ToOctalString ();

5. convert other hexadecimal values to decimal values

ParseInt (String, radix );

For example, int a = Integer. parseInt ("110", 2 );

6. JDK1.5New features after version

Integer x = 4; automatically boxed. Equivalent to Integer x = new Integer (4 );

X = x + 2; // perform automatic unpacking. Changed to int type. And 2. The binning of x is equivalent to x. intValue ().

VII. Supplement

1. If: Integer m = 128; Integer n = 128; then: x = y, the result is false.

2. If: Integer a = 127; Integer B = 127; then: a = B, the result is true. Because a and B point to the same Integer object. When the value is within the byte range, for new features, if the value already exists, no new space will be opened.

8. Exercise

/* Sort the values in a string in ascending order. "20 78 9-7 88 36 29"


1. sorting, familiar

2. Convert the string into a substring to obtain the value to be sorted in the string. It is found that the original string is separated by spaces. Therefore, you can use the cut method of the string object to convert a large string to a small string.

3. How to convert the obtained numeric string to the int type. String --> basic data type. You can use the packaging class. */

1 import java. util. arrays; 2 class wrapperClassDemo {3 private static final String SPACE_SEPARATOR = ""; 4 public static void main (String [] args) {5 String numStr = "20 78 9-7 88 36 29"; 6 System. out. println (numStr); 7 numStr = sortStringNumber (numStr); 8 System. out. println (numStr); 9} 10 // String sorting function 11 public static String sortStringNumber (String numStr) {12 // convert a numeric String to a character array 13 String [] str_arr = st RingToArray (numStr); 14 15 // convert the character array to the int array 16 int [] num_arr = toIntArray (str_arr ); 17 18 // sort the int array in ascending order 19 mySortArray (num_arr); 20 21 // convert the int array to the String 22 String temp = numToString (num_arr ); 23 24 return temp; 25} 26 // define the String to be converted into a String Array Function 27 public static String [] stringToArray (String numStr) {28 String [] str_arr = numStr. split (SPACE_SEPARATOR); 29 return str_arr; 30} 31 // define a string array to convert it to an int [] array 32 public static int [] ToIntArray (String [] str_arr) {33 int [] int_arr = new int [str_arr.length]; 34 for (int I = 0; I <str_arr.length; I ++) {35 int_arr [I] = Integer. parseInt (str_arr [I]); 36} 37 return int_arr; 38} 39 // sorts int [] 40 public static void mySortArray (int [] num_arr) {41 Arrays. sort (num_arr); 42} 43 // define int [] array to convert String function 44 public static String numToString (int [] num_arr) {45 // StringBuffer sb = new StringBuffer ();/ /Multithreading, using StringBuffer46 StringBuilder sb = new StringBuilder (); // single thread, using StringBuilder47 for (int x = 0; x <num_arr.length; x ++) {48 if (x! Num_arr.length-1) 49 sb. append (num_arr [x] + SPACE_SEPARATOR); 50 else51 sb. append (num_arr [x]); 52} 53 return sb. toString (); 54} 55}


Which of the following methods does a String or StringBuffer Class Object change itself when it is called?


String is a value class. Each modified method returns a new String.

Length is the query method and does not change

How to convert String data to StringBuffer?

StringBuffer (String str)
Constructs a string buffer and initializes its content to the specified string content.

This is a StringBuffer constructor.

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.