String operation class string

1.String

1.1 String overview

       (1) The String class is under the java.long package. You do not need to import the package when using it.

       (2) The String class represents a String. All String literals (such as "abc") in the java program are implemented as examples of this example, that is, all double quoted strings in the java program are objects of the String class.

       (3) Strings are immutable and their values cannot be changed after creation.

       (4) The String class is decorated with the final modifier, indicating that it has no subclasses and cannot be inherited.

1.2 String construction method

       (1) String() creates a blank string object without any content;

       (2) String (byte [] bytes, int offset, int length) creates a string object according to the contents of the byte array, int offset - the starting position of the array, int length - the number of bytes converted);

       (3) String (char [] CHS, int offset, int length) creates a string object according to the contents of the character array. Int offset -- the starting position of the array, and int length -- the number of characters converted;

       (4) String (Sting original) string constant creates a string object; For example, String s = "abc";

       (5) String(StringBuffer buffer) -- converts a StringBuffer to a string

                String (StringBuilder) -- convert StringBuilder to string

Example:

public class StringTest {

       public static void main(String[] args) {

              //String() creates a blank string object that contains nothing

              String str1=new String();

              //String (byte [] bytes, int offset, int length) creates a string object according to the contents of the byte array

              byte bys[]={97,98,99,100};

              //String str2=new String(bys); That's right, you can

              //String str2=new String(bys,1,3);// Output bcd

              String str2=new String(bys,0,bys.length);

              System.out.println("str2=="+str2);

              //String (char [] CHS, int offset, int length) creates a string object according to the contents of the character array

              char chs[]={'a','b','c','d'};

              String str3=new String(chs,0,chs.length);

              System.out.println("str3=="+str3);//abcd

              //String (Sting original) string constant creates a string object;

              String str4=new String("hello,world");

//It can also be simplified to

              String str5="hello,world";   

              System.out.println("str4=="+str4);

              System.out.println("str5=="+str5);

       }

}

1.3 characteristics of string object

       (1) For string objects created through new, each new will apply for a memory space. Although the contents are the same, the address values are different.

Example:

        char[] chs={'a','b','c'};

       String s1=new String(chs);

       String s2=new String(chs);

       First, the JVM will create a character array, and then each time it creates a new address, but the string contents referenced by s1 and s2 are the same.

       (2) As long as the character sequence is the same (order and case), no matter how many times it appears in the program code, the JVM will only create a String object and put it in the String constant pool.

such as

String s1="abcd";

String s2="abcd";

       Firstly, the JVM will create a String object and put it in the String constant pool for s1 reference, and then s4 directly refers to the String objects in the String constant pool. They are essentially the same object.

Refer to the figure below for details

Question: String   s1=new String("abc"); Several objects were created

       A: two. First, create a String object "abc" in the constant pool, and then new an object in the heap.

1.4 string comparison

Use = = for comparison

  1. Basic type: compares whether the data values are the same
  2. Composite type: compares whether the address values are the same

A string is an object that compares whether the contents are the same. It is implemented through a method called: equals()

Example:

public class Test {

       public static void main(String[] args){

              //Get the object by constructing the method

              char[] chs={'a','b','c'};

              String s1=new String(chs);

              String s2=new String(chs);

              //Get the object by direct assignment

              String s3="abc";

              String s4="abc";



              System.out.println(s1.equals(s3));//true

              System.out.println(s1.equals(s4));//true

              System.out.println(s3.equals(s4));//true

        }

}

Interview question: "what is the difference between" = = "and equals method?

1. "= =" is often used to compare basic data types. There are eight basic data types: byte, short, long, double, char, int, float and boolean. Because variables directly store their values, use "= =" to compare and compare their values. However, the composite data type uses "= =" to compare its heap memory address [reference address].

2. "Equals" also compares its heap memory address for composite data types (variables that cannot act on basic data types). Because the String class overrides the equals method, the String class "equals" compares whether the contents of the stored objects are equal.

2. Common methods of string

Common methods of String (object. Blue)

effect

char charAt(int index)

Gets the character element at the specified position from the original string

String concat(String str)

Concatenates the specified string to the end of the string

boolean contains(CharSequence s)

Determines whether the specified string data exists in the original string

boolean endsWith(String suffix)

Tests whether this string ends with the specified suffix

boolean startsWith(String prefix)

Tests whether this string starts with the specified prefix

byte [ ] getBytes()

byte[ ] getBytes(String charsetName)

Converts a string into a byte array by default character encoding

Converts a string into a byte array through the specified character encoding

int indexOf(String str)

Returns the index position at which the specified substring first appears within the string

lastIndexOf(String str)

Returns the index in the last occurrence of a specified substring

boolean isEmpty()

Judge whether the string is an empty string. When it is true, the string length must be 0

int length()

Returns the length of this string

boolean matches(String regex)

Judge whether the string data conforms to the regular expression

String replace(CharSequence old, CharSequence new)

Replaces each substring of the string that matches the literal target sequence with the specified literal replacement sequence

String[ ] split(String regex)

Splits a string into an array of strings by the specified symbol

String substring(int beginIndex)

String substring(int beginIndex, int endIndex)

Intercepts a substring from the specified start position to the end of the string

Intercepts a substring from the specified start position to the specified end position

char[]  toCharArray()

Convert this string to a new character array

String toLowerCase()

Capital to lowercase

toUpperCase()

Lowercase to uppercase

String trim()

Remove the two leading spaces of the original string

Example:

public class StringFangFa {



       public static void main(String[] args) {

              //Create a string object

              String str1=new String("hello,world");

              //charAt(int index) gets the character element at the specified position from the original string

              System.out.println(str1.charAt(4));//o

              //concat(String str) concatenates the specified string to the end of the string

              System.out.println(str1.concat("!Hello"));//hello,world! Hello

              //Contains (charsequences) determines whether the specified string data exists in the original string

              System.out.println(str1.contains("hello"));//true

              System.out.println(str1.contains("hi"));//false

              //Create an array of names

              String names[]={"Zhang San","Li Si","Wang Wu","Li sisi","Zhang Sanfeng"};

              //endsWith(String suffix) tests whether the string ends with the specified suffix, and outputs the value ending with the specified suffix

              /*Traversal array names

               * for(String name:names){

                     System.out.println(name);

              }*/

              for(String name:names){

                     if(name.endsWith("thinking")){

                     System.out.println(name);

                     }

              }//Li sisi

              // startsWith(String prefix) tests whether the string ends with the specified prefix and outputs the value starting with the specified prefix

              for(String name:names){

                     if(name.startsWith("Zhang")){

                     System.out.println(name);

                     }

              }//Zhang Sanfeng

              /*          

               byte[] getBytes() Converts a string into a byte array by default character encoding

               byte[] getBytes(String charsetName) Converts a string into a byte array through the specified character encoding

               Before implementing the function, you have to have a string after the byte array is converted, so first create the byte array, then create the string object, and then turn back to the byte array

              */

              byte byts[]={97,98,99,100};//Byte array

              String str2=new String(byts);//To string object

              byte byts2[]=str2.getBytes();//The default character encoding is returned to the byte array

              //byte byts3[]=str2.getBytes("utf-8");// The specified character encoding is returned to the byte array. If there is an error, the exception class will handle it, and throws it up

              //System.out.println(byts2); If the array is output, it needs to be traversed, and the direct output is garbled

              for(byte by:byts2){

                     System.out.println(by);

              }

              //indexOf(String str) returns the index position where the specified substring first appears in the string

                     System.out.println(str1.indexOf("orld"));//7

                     System.out.println(str1.indexOf("llo"));//2

              //lastIndexOf(String str) returns the index position where the specified substring last appeared in the string

                     String str3=new String("hello,world,hello,world,hello");

                     System.out.println(str3.lastIndexOf("llo"));//26

              //isEmpty() determines whether the string is empty

                     System.out.println(str3.isEmpty());//false

              //length() returns the length of this string

                     System.out.println(str3.length());//29

              //replace(CharSequence old, CharSequence new)

              //Replaces each substring of the string that matches the literal target sequence with the specified literal replacement sequence

                     System.out.println(str3.replace("or", "zj"));//hello,wzjld,hello,wzjld,hello

              //split(String regex) splits a string into an array of strings by the specified symbol

                     String arr[]=str3.split(",");

                     System.out.println(arr[0]);//hello

                     System.out.println(arr[3]);//word

              /*substring(int beginIndex)

              Intercepts a substring from the specified start position to the end of the string

              substring(int beginIndex, int endIndex)

              Intercepts a substring from the specified start position to the specified end position*/

                     System.out.println(str3.substring(3));//lo,world,hello,world,hello

                     System.out.println(str3.substring(3, 15));//lo,world,hel

              //toCharArray() converts this string to a new character array

              //Similarly, you have to have character arrays and string objects

                     char ch1[]={'w','e','i'};

                     String str4=new String(ch1);

                     char ch2[]=str4.toCharArray();

                     for(char ch:ch2){

                            System.out.println(ch);

                     }

              //toLowerCase() uppercase to lowercase

              //toUpperCase() lowercase to uppercase

                     System.out.println(str4.toLowerCase());//wei

                     System.out.println(str4.toUpperCase());//WEI

              //trim() removes the two leading spaces of the original string

                     System.out.println(str4.trim());

       }            

}

3. Encapsulation

parseXXX(String) of the encapsulated class provided by the basic type   str)

       int parseInt(String  str)  / double  parseDoule(String  str)

       boolean parseBoolean(String  str).......

       The above group parseXXX(String)   str) methods can only be called by encapsulated classes of basic types.

       (1) Only 8 basic data types have corresponding encapsulation types;

       (2) Encapsulation class - a composite of 8 basic data type objects

Basic data type

Encapsulation class type

byte

Byte

short

Short

int

Integer

long

Long

float

Float

double

Double

char

Character

boolean

Boolean

(3) The basic data type has no methods and variables to call. Encapsulated classes have callable variables and methods.

For example:

       double   dou=12.5;   // There is no method available for a variable of type double

       Double   dou=new Double(12.5); //Double object, with variables and methods available.

       Double is the encapsulated class of double

       (4) The basic data type only has data allocation in the stack area of memory, and the stack area and heap area of encapsulated [composite data type] memory have memory allocation.

       (5) The default initial value is different. int---0, Integer---null

       (6) When installing classes, create objects and new + construction methods

       (7) Differences between basic data types and corresponding encapsulation classes

Basic data type

Encapsulation class

Basic type

class

Variable, there are no methods and variables to call

Constructed objects provide variables and methods

There is data allocation only in the stack area of memory

Both stack and heap areas of memory have memory allocation

Have their own default data values

The default value is null

4. Automatic packing and unpacking

4.1 automatic packing

       Auto boxing: convert the basic data type to the corresponding encapsulation class type

       (1) Construction method of encapsulation class;

       (2) Assign the basic data type variable / data value directly to the corresponding encapsulated class variable       

 public static void main(String[] args) {

              //Automatic packing

              //1. Construction method of encapsulation class

              Integer int1=new Integer(100);

                     //perhaps

              int a=100;

              Integer int2=new Integer(a);

              //2. Assign the basic data type variable / data value directly to the corresponding encapsulated variable

              Double dou=12.5;//①

              /*          

              double dou1=12.5;

              Double dou2=dou1;②

              ①②All right*/

4.2 automatic unpacking

       Automatic unpacking: convert encapsulation type to basic data type [direct assignment]

              //Automatic unpacking

              Character cr=new Character('A');

              char value=cr;

5. Conversion between string class and basic data type

5.1 converting basic data type to String

Convert basic data type to String [static String valueof (data value / variable of basic data type)] example:       

              int num1=100;

              String str01=String.valueOf(num1);

              System.out.println(str01.length());

             

              double dou01=12.5;

              String str02=String.valueOf(dou01);        

5.2 converting string to basic type

       To convert a String to a basic data type, you need to rely on the encapsulation class corresponding to the basic data type and use the static method parseXXX(String) of the encapsulation class of the basic data type   str) converts a String to a base type.

Example:              

//We can encapsulate the static method parseXXX(String) of the class through the basic data type    str) converts a string to a base type

              String  str1="12.5";

              double dou3=Double.parseDouble(str1);

              System.out.println(dou3+1);

             

              String boo1="true";

              boolean  boo2=Boolean.parseBoolean(boo1);

              if(boo2){

                     System.out.println("Basic type");

              }else{

                     System.out.println("String type");

              }

6. Conversion between string class and byte array

6.1 String class and byte array

         (1) Convert String class to byte array

              byte[] getBytes()/byte[] getBytes(String charsetName) of String class

         (2) Byte array conversion String type

              Construction method of String class String(byte[] bytes, int offset, int length)

6.2 String class and character array

         (1) Convert String class to character array

              "char [] of String class   toCharArray()”

         (2) Character array conversion String type

              Construction method of String class "String(char[] value, int offset, int count)"

7. StringBuffer and StringBuffer

7.1 StringBulider

7.1.1 StringBuilder overview

       (1) Let's look at an example and observe the change of address value

              String s="hello";

              s +="world";// Equal to s=s+"world";

              System.out.println(s);

          Output helloworld

       First, the heap constant pool has a hello of 001, the stack area has an S OO1, then the heap area 002 world, followed by + helloworld, all have a helloworld of 003, and then assigned to s, and the stack area s becomes 003.

       Conclusion: if the String is spliced, a new String object will be constructed each time, which is time-consuming and a waste of storage space, and this operation is inevitable. Therefore, java provides a kind of solution to this problem ----- StringBuilder

       (2) StringBuilder is a variable string class. We can regard it as a container. Variable means that the content in the StringBuilder object is variable.

7.1.2 StringBuilder construction method

       (1) StringBuilder() constructs an empty StringBuilder object with an initial capacity of 16 characters.

       (2) StringBuilder(String str) constructs a StringBuilder object initialized to the specified string content.

       (3) StringBuilder(CharSequence seq) creates a new StringBuilder object from other StringBuilder objects.

       (4) StringBuilder(int capacity) constructs an empty StringBuilder object with initial capacity specified by the capacity parameter

Example:                         

    //(1) StringBuilder() constructs an empty StringBuilder object with an initial capacity of 16 characters.

                     StringBuilder str1=new StringBuilder();

              //(2) StringBuilder(String str) constructs a StringBuilder object initialized to the specified string content.

                     String s="hello";

                     StringBuilder str2=new StringBuilder(s);

              //(3) StringBuilder(CharSequence seq) creates a new StringBuilder object from other StringBuilder objects.

                     StringBuilder str3=new StringBuilder("hello");

              //(4) StringBuilder(int capacity) constructs an empty StringBuilder object with the initial capacity specified by the capacity parameter

                     StringBuilder str4=new StringBuilder(3);

7.1.3 StringBuilder instance method

Return value

method

int

capacity() returns the current capacity

int

indexOf(String   str) returns the index of the first occurrence of the specified substring.

int

lastIndexOf(String   str) returns the index of the string appearing on the rightmost side of the specified substring

int

length() returns the length in characters.

char

charAt(int   index) returns the char character value at the specified index

StringBuilder

append(Object o) appends the string representation of the parameter to the sequence

StringBuilder

delete(int   start, int   end) delete the characters in the substring of this sequence

StringBuilder

deleteCharAt(int   index) delete the specified position of char in this sequence

StringBuilder

insert(int   offset, Object o) inserts the string representation of the parameter into the position specified in this sequence.

StringBuilder

reverse() causes the character sequence to be replaced by the opposite of the sequence

StringBuilder

replace(int   start, int   end, String   str) replaces the string in the substring of this sequence with the characters in the specified string

String

substring(int   start) returns a new String containing a subsequence of the characters currently contained in this character sequence

String

substring(int   start, int   end) returns a new String containing a subsequence of the characters currently contained in this sequence

String

toString() returns a string representing the data in this order

Note: (1) StringBuilder capacity extension rule = = current capacity * 2 + 2

            (2) Position at end does not contain

            (3) Pay attention to the return value type of the StringBuilder method, and make no mistake about the receiving type; In addition, the return value type is StringBuilder, which means that the previous value has been changed.

Example:

public class StringBuilderTest2 {

       public static void main(String[] args) {

              StringBuilder str1=new StringBuilder();

              //append(Object o) appends the string representation of the parameter to the sequence.

              System.out.println(str1.append("hello"));//hello

              //capacity() returns the current capacity

              System.out.println(str1.capacity());//16

              //StringBuilder capacity extension rule = = current capacity * 2 + 2, if it exceeds 16, it shall be handled according to the rule

              StringBuilder str2=new StringBuilder();

              str2.append("hahhojdppmlkjpjwoh");

              System.out.println(str2.capacity());//34

              //charAt(int index) returns the char character value at the specified index.

              System.out.println(str1.charAt(1));//e

              //delete(int start, int end) deletes the characters in the substring of this sequence. Note that the end position is deleted before the specified position, and the end position does not contain

              System.out.println(str1.delete(1, 3));//hlo

              //deleteCharAt(int index) deletes the specified position of char in this sequence

              System.out.println(str1.deleteCharAt(2));//hl

              str1.append("wohenhao");

              System.out.println(str1);//hlwohenhao

              //indexOf(String str) returns the index of the string where the specified substring first appears.

              System.out.println(str1.indexOf("e"));//5

              System.out.println(str1.lastIndexOf("h"));//7

              //insert(int offset, Object o) inserts the string representation of the parameter into the specified position in this sequence.

              System.out.println(str1.insert(1,"ss"));//hsslwohenhao

              //length() returns the length (number of characters)

              System.out.println(str1.length());//12

              //reverse() causes the character sequence to be replaced by the opposite of the sequence.

              System.out.println(str1.reverse());//oahnehowlssh

              //replace(int start, int end, String str) replaces the String in the substring of this sequence with the characters in the specified String.

              //Similarly, this end position does not contain

              System.out.println(str1.replace(1, 4, "ii"));//oiiehowlssh

              //substring(int start) returns a new String containing the subsequence of characters currently contained in this character sequence.

              System.out.println(str1.substring(2));//iehowlssh

              //substring(int start, int end) returns a new String containing the subsequence of characters currently contained in this sequence.

              System.out.println(str1.substring(2,6));//ieho

              System.out.println(str1.substring(4,7));//how

              //toString() returns a string representing the data in this order.

              str1.toString();

              System.out.println(str1.toString());

       }

}

7.1.4 StringBuilder and String conversion

              (1) StringBuilder to String: toString() of StringBuilder;

                     Construction method of String (StringBuilder)

              (2) String to StringBuilder: construction method of StringBuilder

7.2 StringBuffer

       The StringBuffer class is similar to the StringBuilder class

7.2.1 StringBuffer construction method

  • StringBuffer() constructs an empty StringBuffer object with an initial capacity of 16 characters;
  • StringBuffer(CharSequence   seq) create a new StringBuffer object through other StringBuffer objects;
  • StringBuffer(int   capacity) construct an empty StringBuffer object with initial capacity specified by the capacity parameter;
  • StringBuffer(String   str) constructs a StringBuffer object initialized to the specified string content.

7.2.2StringBuffer instance method

  • StringBuffer append(Object o) appends the string representation of the parameter to the sequence.
  • int   capacity() returns the current capacity.
  • char       charAt(int   index) returns char at the specified index.
  • StringBuffer delete(int   start, int   end) delete the characters in the substring of this sequence.
  • StringBuffer deleteCharAt(int   index) delete the specified position of char in this sequence.
  • int   indexOf(String   str) returns the index within the string where the specified substring first appears.
  • int lastIndexOf(String   str) returns the index within the string that appears at the far right of the specified substring.
  • StringBuffer insert(int   offset, Object o) inserts the string representation of the parameter into the position specified in this sequence.
  • int   length() returns the length in characters.
  • StringBuffer reverse() causes the character sequence to be replaced by the opposite of the sequence.
  • StringBuffer replace(int   start, int   end, String   str) replaces the string in the substring of this sequence with the characters in the specified string.
  • String    substring(int   start) returns a new string containing a subsequence of the characters currently contained in this character sequence.
  • String    substring(int   start, int   end) returns a new string containing a subsequence of the characters currently contained in this sequence.
  • String    toString() returns a string representing the data in this order.

7.2.3 StringBuffer and String conversion

(1) StringBuffer to String: toString() of StringBuffer;

                     Construction method of String(StringBuffer builder)

       (2) String to StringBuffer: construction method of StringBuffer R

Example:

public class StringBufferTest {

       public static void main(String[] args) {

              StringBuffer str1=new StringBuffer();

              System.out.println("No, append Previous initial capacity=="+str1.capacity());

              str1.append("hello");

              str1.append(1234);

              str1.append(true);

              str1.append(12.5);

              str1.append("world");

              System.out.println("str1=="+str1);

              System.out.println("append Capacity after=="+str1.capacity());

              System.out.println("StringBuilder Capacity expansion rule==Current capacity*2+2");

              System.out.println("charAt(3)=="+str1.charAt(3));

              System.out.println("delete(13,17)=="+str1.delete(13,17));

              System.out.println("deleteCharAt(3)=="+str1.deleteCharAt(3));

              System.out.println("indexOf('l')=="+str1.indexOf("l"));

              System.out.println("lastIndexOf('l')=="+str1.lastIndexOf("l"));

              System.out.println("insert(12,12.5)=="+str1.insert(12,12.5));

              System.out.println("length=="+str1.length());

              System.out.println("replace(8,12,'false')=="+str1.replace(8,12,"false"));

              //System.out.println("reverse()=="+str1.reverse());

              System.out.println("substring(4, 8) =="+str1.substring(4, 8));

       }

}

7.3 differences between StringBuilder and StringBuffer

  • StringBuilder -- a variable character sequence that does not guarantee thread synchronization [thread safety]. Fast access    jdk1.5
  • StringBuffer --- a variable character sequence to ensure thread safety. The access speed is slow    JDK1.0

7.4 differences between string and StringBuilder/StringBuffer

String

StringBuilder

StringBuffer

Variable or not

Immutable

variable

variable

Thread safe or not

Non thread safe

Non thread safe

Thread safety

running speed

slow

fast

Faster

Operation

A small number of string operations

Large number of character operations under single thread

A large number of string operations under multithreading

Keywords: Java

Added by bossman on Wed, 10 Nov 2021 12:18:16 +0200