String, StringBuilder, and StringBuffer classes,

Source: Internet
Author: User
Tags array to string

String, StringBuilder, and StringBuffer classes,
Introduction

String/StringBuilder/StringBuffer can all create String objects that inherit from the Object class.

Once a String object is created, its space remains unchanged and data cannot be added or deleted to it. Even if the replace () method is provided, a character is replaced by a character. In short, its space size remains unchanged.

The latter two are variable space String objects, so they provide the append () method, insert () method, delete () and other functions to modify space data. The StringBuilder class is a simplified version of the StringBuffer class, but it is more efficient and provides the same functions. Therefore, when StringBuilder can meet the requirements, we recommend that you use the StringBuilder class instead of the StringBuffer class.

StringBuilder class and StringBuffer class

They are used in the same way. Take the StringBuilder class as an example.

This class is used to create a String class and to insert or delete data to or from String data. The two main methods are append () and insert ().

Construct a String object:

StringBuilder sb1 = new StringBuilder (); // The object contains an empty string StringBuilder sb2 = new StringBuilder ("ac"); // The object contains the string acSystem. out. println (sb1); System. out. println (sb2 );

Append ()The method is used to append String data to the end of an existing String object. If the data is not of the String type, the toString () method is used to convert it to the String type.

StringBuilder sb = new StringBuilder("ac");sb.append("xx");sb.append(3);sb.append(3.12);System.out.println(sb);  //return value: acxx33.12

Insert ()This method is used to insert data to a specified position.

StringBuilder sb = new StringBuilder("ac");sb.append("xx");     //acxxsb.append(3);        //acxx3sb.append(3.12);     //acxx33.12sb.insert(3,"x");    //acxxx33.12sb.insert(3,2.12);   //acx2.12xx33.12

There are also some common String-related methods. If the start and end methods are included, the end boundary is generally not calculated.

  • charAt(int n): Return the character at the specified character position in the object. The position starts from 0.
  • delete(int start,int end): Delete the substring from the start position to the end position and return it. Does not contain the end boundary.
  • deleteCharAt(int n): Delete the characters at the specified position and return them.
  • indexOf(String str): Obtain the position where str appears for the first time from the left.
  • lastIndexOf(String str): Obtain the position where str appears for the first time from the right.
  • lenght(): Returns the string length.
  • replace(int start,int end,String str): Replace the start and end positions (excluding the end boundary) with str.
  • reverse(): Reverse string.
  • substring(int n): Truncate the substring from position n to the end.
  • substring(int start,int end): Truncates a substring from the start position to the end position (excluding the end boundary.
  • toString(): Override the toString () method of the Object class. Converts a StringBuilder object to a String object.
Difference between StringBuilder and StringBuffer

Buffer (short for convenience) is synchronized to ensure the security of multiple threads. After thread 1 append (), the lock must be released after synchronization. Thread 2 and thread 3 can continue to operate (such as delete) the data in this buffer. However, to ensure that the data has been synchronized, the efficiency is slightly lower.

The Builder does not guarantee the security of multithreading. After thread 1 append () data, thread 2 can directly operate (such as delete) the data in this cache zone. However, because you do not need to confirm whether the data is synchronized, the efficiency is higher than the Buffer.

Their key point is whether multithreading is secure. For a single thread, they are always secure. In this case, Builder should be used to improve efficiency.

String type

Several important methods:

  • Equals (Object obj) and inclusignorecase (Object obj)
    Compare whether two objects are equal. After the equals () method of the String class is rewritten, the comparison behavior is: only when the content of the two objects is equal, equals () returns true.

    String a = String.valueOf(123);String b = new String("123");System.out.println(a.equals(b));  //true
  • CompareTo (String str) and compareToIgnoreCase (String str)
    Inherited from the Comparable interface, the rewritten method compares String objects with str in alphabetical order. If the String object is smaller than str, a negative number is returned. If the String object is larger than str, a positive number is returned. If the String object is equal, 0 is returned. CompareTo () returns 0 only when equals () returns true.

  • Split (String regexp): divides String into String [] arrays according to the specified regexp.

    String b = new String("123 xyz 456");String[] c = b.split(" ");      //c={"123","xyz","456"}
  • ValueOf (type value): converts a data value of the given type to a String type and encapsulates it into a String object.

    String a = String.valueOf(123);   //int --> StringString a = String.valueOf(12.3);  //double --> String

There are other methods:

  • charAt(int n): Return the character at the specified character position in the object. The position starts from 0.
  • concat(String str): Connects the specified string 'str' to the end of the string.
  • contains(String str): Whether the String object contains the str substring. If it is true, true is returned. Otherwise, false is returned.
  • contentEquals(String str): If the content of the String object is str, true is returned; otherwise, false is returned.
  • contentEquals(StringBuffer s): If the String object and StringBuffer object s have the same content, true is returned; otherwise, false is returned. It also applies to StringBuilder class objects.
  • startsWith(String str): Test whether the String object is prefixed with the str substring. Returns the boolean type.
  • endsWith(String str): Test whether the String object is suffixed with the str substring. Returns the boolean type.
  • indexOf(String str): Obtain the position where str appears for the first time from the left.
  • lastIndexOf(String str): Obtain the position where str appears for the first time from the right.
  • lenght(): Returns the string length.
  • isEmpty(): Whether the String object contains data. That is, when length returns 0, it is true.
  • matchs(String regexp): Whether the String object can be matched by the regular expression regexp.
  • replace(char o,char n): Replace the o character in the String with the new n character.
  • substring(int n): Truncate the substring from position n to the end.
  • substring(int start,int end): Truncates a substring from the start position to the end position (excluding the end boundary.
  • toLowerCase(): Return lowercase letters.
  • toUpperCase(): Return lowercase letters.
  • trim(): Returns a copy of the String that ignores leading and trailing spaces.
  • toString(): Override the toString () method of the Object class. Converts a String object to a String object. In fact, it is of the String type.
  • toCharArray(): Returns a String as a char array.
  • getChars(s,e,char[] c,c_s): Copy the characters from s position to e end (excluding e boundary position) in the String object to the c_s position in char array c.
    String s = new String("acde");char[] sb1 =  s.toCharArray();  //sb1 = {a,c,d,e}char[] sb2 = new char[3];s.getChars(0,3,sb,0);           //sb2 = {a,c,d}
Int [] array to String [] Array

For example, you have an int [] array and want to convert it to String []. This is equivalent to rewriting a "String [] toString (int [] arr)" method.

import java.util.*;    //int[]-->String[]    public static String[] toString(int[] arr) {        String[] sarr = new String[arr.length];        for (int i=0;i<arr.length;i++) {            sarr[i] = Integer.valueOf(arr[i]).toString();        }        return sarr;    }public class TestToString {    public static void main(String[] args) {        int[] arr = {12,3,4,5,66};        String[] sarr = toString(arr);        System.out.println(Arrays.toString(sarr));    }}
Int [] array to String

For example, the int [] Array {1, 2, 3, 4} is converted into a string and the result is "1 2 3 4 ". Convert the values in the array to strings and separate them with spaces.

public class IntToString {    // int[] --> String    public static String toString(int[] arr) {        StringBuilder sarr = new StringBuilder();        for (int i=0;i<arr.length;i++) {            if (i != arr.length - 1) {                sarr.append(arr[i] + " ");            } else {                sarr.append(arr[i]);            }        }        return sarr.toString();    }    public static void main(String[] args) {        int[] arr = {12,3,4,5,66};        String sarr = toString(arr);        System.out.println(sarr);    }}
Reprinted please indicate the source: Success!

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.