Detailed strings - String, StringBuffer and StringBuilder

Originally the contents of this blog, I intend following code examples to explain little by little through, but I found that, in fact, where the knowledge is still pretty important.
And, string type, in any programming language is to be taken seriously, so today specifically wrote a blog post to explain this knowledge!



First, what is the string it?
I believe that learning C language students to know:

String is a string of data (a sequence of characters) a plurality of characters of
the string can be seen as an array of characters

Yes, then Java, is also the case, however, compared to the C language, Java such a high-level language, there is a good package for the string class, and that is our theme of this blog - String class .

String class:

In my previous post, I mentioned String class, but they talk about this class of variable is a string type, and all types of variables and the sum will be converted to a string of strong type.
Well, now, I have to explain the nature and other commonly used methods of the String class:

Now, I have to show under common API String class :

  1. String class constructor :

Common constructor :

  • public String ():
    Empty construction
  • public String (byte [] bytes) :
    the byte array translated into strings
  • public String (byte [] bytes, int index, int length):
    the part of the string into a byte array transfer (index: represented by an index number from the start, length represents the length)
  • public String (char [] value) :
    the array of characters transformed into a string
  • public String (char [] value, int index, int count):
    The transfer of a portion of an array of characters to a string
  • public String (String original):
    string constant value translated into strings
  1. String class determining function :
  • public boolean equals (Object obj):
    compare strings have the same contents, case sensitive
  • public boolean equalsIgnoreCase (String str):
    String comparison content is the same, ignoring case
  • public boolean contains (String str):
    determining whether the character string contains the character string passed in
  • : public boolean startsWith (String str)
    at the beginning of the string is determined whether the passed string
  • public boolean endsWith (String str):
    determines whether the end of the string to the string passed in
  • public boolean isEmpty():
  1. String class acquisition function :
  • public int length ():
    Get the length of the string.
  • public char charAt (int index):
    Gets the index position of the character
  • public int indexOf (int ch):
    Returns the character index within this string of the first occurrence.
  • public int indexOf (String str):
    Returns the index of the string in the first occurrence of the string.
  • public int indexOf (int ch, int fromIndex):
    Returns the index of the character string appears in the specified position from the first.
  • public int indexOf (String str, int fromIndex):
    Returns the index of the string in this string appears first from the designated location.
    Incidentally series can lastIndexOf
  • public String substring (int start):
    From the start position of the specified string taken, at the end of the default.
  • public String substring (int start, int end):
    starting at the specified position to a specified position of the end character string taken.
  1. String class conversion function :
  • public byte [] getBytes ():
    converts a string to an array of bytes.
  • public char [] toCharArray ():
    converts a string to an array of characters.
  • public static String valueOf (char [] chs):
    the array of characters into a string transfer.
  • public static String valueOf (int i) :
    the int type data into a string.
    Note: valueOf String class method can be any type of data into a string.
  • public String toLowerCase ():
    string to lower case.
  • public String toUpperCase ():
    string transfer to uppercase.
  • public String concat (String str):
    the string concatenation
  1. String class additional features :

1.String replacement function:

  • public String replace (char old, char new)
    specified character interchange
  • public String replace (String old, String new)
    The specified string interchangeable

2.String removal string two spaces:

  • public String trim () remove both ends of a space

3.String comparison of two strings lexicographically
> - public int compareTo (String str )
will control the ASCII code table from the first letter of a subtraction result of the subtraction is returned to
if the first few letters based on two different the length of the string is returned subtraction result of this subtraction is
the same even if the return string is exactly 0

  • public int compareToIgnoreCase (String str)
    with the above as just ignore case compare

Let's take a show piece of code:

package com.mec.study;

public class AboutString {
    
    public static void main(String[] args) {
        //String的第一种生成方法:
        String str1 = new String("第一种生成方法");
        //String的第二种生成方法:
        String str2 = "第二种生成方法";
        //String的第三种生成方法:
        String str3 = String.valueOf(123456);
        
        //展示字符串长度:
        System.out.println(str1.length());
        //取字符串字串:
        System.out.println(str2.substring(3, 5));
        //其他类型变量的强转,字符串的拼接
        System.out.println(str3 + 321);
        
        String code = null;
        for (int i = 0; i < 3; i++) {
            code = String.valueOf(1000 + i).substring(1);
            System.out.println(code);
        }
    }
    
}

Here Insert Picture Description

The above code, contains a wealth of skills,
so now, I do for a loop last operation above a clarification:
some students may be thinking, why not be the first 22 lines of code written in the form above figure it:

code = String.valueOf(i)

I is incremented to 1000, the most significant bit in turn "removed", as it is not subjected to two-step operation.
I think students, unfortunately, you still questioning my ability, if not them that two steps, then there would be no "automatic complement each number three (fill with zeros)" phenomenon.
Do not believe, let's try:
Here Insert Picture Description
you can clearly see, there is no phenomenon of auto-complete zero!
Such an operation, in fact, after our work in a very commonly used, I hope we can pay attention to them!

We are discussed below string String class features of:

Features:
string once created can not be changed
because the value of the string in constant pool area method of the divided space, an address value assigned

We still have to verify this conclusion by a piece of code:

package com.mec.study;

public class AboutString {
    
    public static void main(String[] args) {
        String str1 = "123abc123defg123wxyz";
        
        System.out.println("原str1: " + str1);
        System.out.println(str1.replace("123", "ABCD"));
        System.out.println("现str1: " + str1);
    }
    
}

Let us look at the results:
Here Insert Picture Descriptionyou can see, we modify the part has not been reflected in the original string Sting class that str has not been changed!
In fact, the results str.replace () is a " new string " String is a new object !

我们不断地去new一个新的对象,相当于不断地去malloc,这样下来,是很浪费时间的!
那么,该如何解决这两点问题呢?

下面本人隆重介绍两个类——StringBuffer类 和 StringBuilder类:

StringBuffer类 和 StringBuilder类:

StringBuffer类 和 StringBuilder类这两个类的API甚至完全一样,但是,为什么要设置两个类呢?
答曰:

StringBuffer类

  • 线程安全性高,但是效率低

StringBuilder类

  • 线程安全性低,但是效率高

那么,本人现在介绍下这两个类:
(由于这两个类的API几乎完全相同,所以,本人在这里通过展示StringBuffer类的API来代表两个类都有的API 的展示)

StringBuffer的构造方法

  • public StringBuffer():
    无参构造方法
  • public StringBuffer(int capacity):
    指定容量的字符串缓冲区对象
  • public StringBuffer(String str):
    指定字符串内容的字符串缓冲区对象

StringBuffer的方法

  • public int capacity():
    返回当前容量。 理论值
  • public int length():
    返回长度(字符数)。 实际值

StringBuffer的添加功能

  • public StringBuffer append(String str):
    可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
  • public StringBuffer insert(int offset,String str):
    在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身

StringBuffer的替换和反转功能:

  • public StringBuffer replace(int start,int end,String str):
    从start开始到end用str替换
  • public StringBuffer reverse():

StringBuffer的截取功能:

  • public String substring(int start):
    从指定位置截取到末尾
  • public String substring(int start,int end):
    截取从指定位置开始到结束位置,包括开始位置,不包括结束位置

注意事项:
返回值类型不再是StringBuffer本身

StringBuffer和String的相互转换:

String --> StringBuffer:

  • By constructing method
  • By append () method

B:StringBuffer --> String:

  • Methods using substring
  • By constructing method
  • By toString () method

As for StringBuilder class, all of the API and StringBuffer classes are about the same, I am here not long-winded.

Now, to show the I, these two classes of strings basic use:

package com.mec.study;

public class AboutStringBuffer {

    public static void main(String[] args) {
        StringBuffer str = new StringBuffer("abc");
        str.append(123);
        System.out.println(str);
    }

}

Here Insert Picture DescriptionFinally, I introduce a very important method - a method of obtaining the current machine computer time (currentTimeMillis ()):
Well, I am now under the StringBuffer to verify exactly how much faster than the speed of String:

package com.mec.study;

public class AboutStringBuffer {

    public static void main(String[] args) {
        //String 类字符串的拼凑耗时测试
        String str = "";
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            str  += 1;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("String拼凑字符串耗时: " + (endTime - startTime) + "毫秒");
        
        //StringBuffer 类字符串的拼凑耗时测试
        StringBuffer strBuffer = new StringBuffer();
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            strBuffer.append(i);
        }
        endTime = System.currentTimeMillis();
        System.out.println("String拼凑字符串耗时: " + (endTime - startTime) + "毫秒");
    }

}

Here Insert Picture Description
In the above test, we can intuitively understand:
if we are dealing with just a simple string constant, or string throughout the program running in little change, we recommend using the String class string;
and if our program the changing requirements of a string, then string StringBuffer class and StringBuilder class string better.

Guess you like

Origin www.cnblogs.com/codderYouzg/p/12418320.html