java String characters, bytes, strings and their common methods

Posted by jeev on Sat, 15 Jan 2022 14:57:44 +0100


String is a very important class for us to learn java. Our future work and study require us to have a full understanding of string. Today, let's learn about string and wish readers success in their studies.

Tip: the following is the main content of this article. The following cases can be used for reference

1, Characters, bytes and strings

1.1 characters and strings

(picture from bit employment class)
Code examples are as follows:

public class TestDemo {
    public static void main(String[] args) {
        //1.public String(char value[])
        char[] val1={'a','b','c'};//a, b and c are stored in the character array
        String str1=new String(val1);//Turns everything in the character array into a string
        System.out.println(str1);//Print abc

        //2.public String(char value[],int offset,int count)
        //Offset means offset. count means how many you want to take from the position where the offset is offset
        char[] val2={'a','b','c','d','e'};
        //For example, a here is the position where the array offset is 0, and b is the position where the array offset is 1
        String str2=new String(val2,1,3);
        //Represents the position offset of 1 from the character array val2, and takes three characters to form a string str2
        //For offset, you can understand it as array subscript
        System.out.println(str2);//Print bcd

        //3.public char charAt(int index)
        //Gets the character at the specified index position. The index starts at 0
        String str3="hello!";
        char ch1=str3.charAt(1);//Gets the character of the 1 subscript
        char ch2=str3.charAt(2);//Gets the character of the 2 subscript
        System.out.println(ch1);//Print e
        System.out.println(ch2);//Print l

        //ps: for 2 and 3, a warning will be given if the subscript is out of bounds
        //4.public char[] toCharArray()
        //Returns a string as an array of characters
        char[] chars=str3.toCharArray();
        //Change the string object pointed to by str3 into a character array, and we use the chars array to receive it
        //Print [h, e, l, l, o,!]

1.2 bytes and strings

(picture from bit employment class)
Code examples are as follows:

public class TestDemo {
//Bytes and strings
    public static void main(String[] args) throws UnsupportedEncodingException {
        //1.public String(byte bytes[])
        //Change byte array to string
        String str1=new String(bytes);
        System.out.println(str1);//Print abcd - the four numbers correspond to the Ascii code as abcd

        //2.public String(byte bytes[],int offset,int length)
        //Changes the contents of a partial byte array to a string
        String str2=new String(bytes,1,3);//It is equivalent to taking 3 from subscript 1
        System.out.println(str2);//Print bcd

        //3.public byte[] getBytes()
        //Returns a string as a byte array
        byte []bytes1=str1.getBytes();
        System.out.println(Arrays.toString(bytes1));//The abcd in str1 will be converted to the corresponding Ascii code
        //Print [97, 98, 99, 100]

        //4.public byte[] getBytes(String charsetNmae)throw UnsupportedEncodingException
        //Code conversion processing
        byte []bytes2=str1.getBytes("utf-8");//ps: an exception is thrown here
        //utf-8 means encoding according to utf-8. You can also change it to GBK and other,
        // It should be noted that if the encoding of other characters other than English is different, the printing result is also different
        System.out.println(Arrays.toString(bytes2));//Print [97, 98, 99, 100]
        String str3="Hello,Ha ha ha";
        //Print [- 28, - 67, - 96, - 27, - 91, - 67, 44, - 27, - 109, - 120, - 27, - 109, - 120, - 27, - 109, - 120]

1.3 summary

So when to use byte [] and when to use char []?
1.byte [] is to process strings byte by byte, which is suitable for network transmission and data storage It is more suitable for binary data operation

2.char [] Yes, String is processed character by character, which is more suitable for text data operation, especially when Chinese is included

2, String common operations

2.1 string comparison

(picture from bit employment class)

Code examples are as follows:

public class TestDemo {
    public static void main(String[] args) {
        //1.public boolean equals(Object anObject)
        //Case sensitive comparison
        String str1="hello";
        String str2="Hello";
        System.out.println(str1.equals(str2));//Print false

        //2.public boolean equalsIgnoreCase(String anotherString)
        //Case insensitive comparison
        System.out.println(str1.equalsIgnoreCase(str2));//Print true

        //3.public int compareTo(String anotherString)
        //Compare the size relationship between two strings and return the difference
        //ASCII code: lower case h 104, upper case H 72
        //Return to 104-72, that is, 32
        //ps: the result is greater than 0, indicating that str1 is greater than str2; Less than 0 indicates that str1 is smaller than str2; Equal to 0, the two are the same;

2.2 string lookup

(picture from bit employment class)
Code examples are as follows:

public class TestDemo {
    //String lookup
    public static void main(String[] args) {
        //1.public boolean contains(CharSequence s)
        //Determine whether a substring exists
        String str="ababcab";
        String tmp="abc";
        boolean flg=str.contains(tmp);//If the str contains tmp, the location where the first tmp appears is returned
        System.out.println(flg);//Return true

        //2.public int indexOf(String str)
        //Find the position of the specified string from the beginning. If the start index of the return position is found, it returns - 1
        int index=str.indexOf(tmp);
        System.out.println(index);//Print 2. Although the first two of str are ab, we want the whole abc, so it is the position of subscript 2
        //indexOf is similar to C's str

        //3.public int indexOf(String str,int fromIndex)
        //Finds the substring position starting at the specified position
        int index1=str.indexOf(tmp,2);//Find tmp from the position of str subscript 2
        int index2=str.indexOf(tmp,3);//Find tmp from the position of str subscript 3
        System.out.println(index1);//Print 2, start from the position of subscript 2, and you can find it
        System.out.println(index2);//Print - 1, starting from the position of subscript 3, cannot be found

        //4.public int lastIndexOf(String str)
        //Find substring position from back to front
        int index3=str.lastIndexOf(tmp);
        System.out.println(index3);//Print 2

        //5.public int lastIndexOf(String str,int fromIndex)
        //Find position from forward to back
        int index4=str.lastIndexOf(tmp,5);//Look from the subscript 5 to the back
        int index5=str.lastIndexOf(tmp,1);//Look from the subscript 1 to the back
        System.out.println(index4);//Print 2
        System.out.println(index5);//Print - 1

        //6.public boolean startsWith(String prefix)
        //Determines whether to start with the specified string
        System.out.println(str.startsWith("a"));//Judge whether str starts with "a" and print true
        System.out.println(str.startsWith("b"));//Judge whether str starts with "b" and print false

        //7.public boolean startsWith(String prefix,int toffset)
        //Judge whether to start with the specified string from the specified position
        System.out.println(str.startsWith("c", 2));//Print false
        //Judge whether str starts with subscript 2 and starts with c - that is, judge whether subscript 2 is "c"
        System.out.println(str.startsWith("a", 2));//Print true

        //8.public boolean endsWith(String suffix)
        //Determines whether to end with the specified string
        System.out.println(str.endsWith("ac"));//Whether str ends with the string ac and prints false
        System.out.println(str.endsWith("ab"));//Whether str ends with string ab and prints true

2.3 string substitution

(picture from bit employment class)
Code examples are as follows:

public class TestDemo {
    //String substitution
    public static void main(String[] args) {
        //1.public String replaceAll(String regex,String replacement)
        //Replace all specified content
        String str="ababcabcdc";
        String ret=str.replace('a','x');
        System.out.println(str);//Print abcabcdc
        //The original str is unchanged -- if the replaced characters are different, a new object is returned
        //For example, str.replace('a','x '); The 'a' and 'x' replaced here are different, so a new object will be returned
        //For example, str.replace('a','a '); 'a' replaced here is the same as' a ', so STR itself will be returned
        System.out.println(ret);//Print xbxbcxbcdc

        String ret1=str.replace("ab","hh");
        System.out.println(ret1);//Print hhchhcdc

        String ret2=str.replaceAll("ab", "hh");
        System.out.println(ret2);//Print hhchhcdc
        //To sum up: replace can replace characters or strings, and replaceAll can only replace strings. Its effect is the same as that of replace

        //2.public String replaceFirst(String regex,String replacement)
        //Replace first content
        String ret3=str.replaceFirst("ab","hh");
        System.out.println(ret3);//Print hhabcabcdc

2.4 string splitting

(picture from bit employment class)
Code examples are as follows:

public class TestDemo {
    //String splitting
    public static void main(String[] args) {
        //1.public String[]split(String regex)
        //Split all strings
        String str="my name is zhangSan&age 19";
        String[] strings=str.split("&");//Split line is&
        for(String s:strings){
        }//Print my name is zhangSan
        // age 19

        //Special case of splitting
        String str1="";
        for(String s1:strings){
        }//You'll find nothing printed here
        //Dot "." Special, if you want to identify "." You need to escape before the dot and add \,
        // But \ It's another meaning. We're going to add another one\
        //That is, \
        for(String s2:strings){
        }//Successfully printed 192 168 1
        //Similar to "." When there are "+" * "|" and they are used as dividing lines, they should be added in front\

        //2.public String[]split(String regex,int limit)
        //Split the string part, and the length of the array is the limit limit
        strings=str1.split("\\.",2);//With "." For split lines, split 2 groups
        for(String s3:strings){
        //Print 192

        //ps: the limit here is the maximum number of groups, not necessarily so many groups
        strings=str1.split("\\.",5);//With "." For split lines, split 2 groups
        for(String s4:strings){
        //Print 192
        //A total of "." Segmentation can only be divided into 4 groups at most, and data greater than 4 can only be divided into 4 groups

        //ps: what happens when there are too many unnecessary symbols in a string?
        String str2="ni hao@ hhh& ooo x";
        strings=str2.split(" |@|&");//If there are many separators to be divided, separate them with |
        for(String s5:strings){
        //Print ni

2.5 string interception

(picture from bit employment class)
Code examples are as follows:

public class TestDemo {
    //String interception
    public static void main(String[] args) {
        //1.public String substring(int beginIndex)
        //Truncates from the specified location index to the end
        String str="abcdefg";
        String sub=str.substring(2);//The substring is extracted from the position of subscript 2 (until the end of the last position)
        System.out.println(sub);//Print cdefg

        //2.public String substring(int beginIndex,int endIndex)
        String sub1=str.substring(2,4);//Extract the substring from subscript 2 to subscript 4 (excluding subscript 4) - close left and open right
        System.out.println(sub1);//Print cd

2.6 other operation methods

Code examples are as follows:

public class TestDemo {
    //Other operation methods
    public static void main(String[] args) {
        //1.public String trim()
        //Remove the left and right spaces in the string and keep the middle space
        String str="   hhh   niHao   ";
        String ret=str.trim();
        System.out.println(ret);//Print HHH nihao
        System.out.println(str);//str unchanged or HHH nihao

        //2.public String toUpperCase()
        //String to uppercase
        String str1="AbcD";
        System.out.println(ret);//Print ABCD

        //3.public String toLowerCase()
        //String to lowercase
        System.out.println(ret);//Print abcd

        //4.public native String intern()
        //String pool operation
        //If there is a constant pool, take the things in the constant pool. If not, put this object in the constant pool

        //5.public String concat(String str)
        //String connection, equivalent to "+", not in the pool
        //Not entering the pool is the result of splicing
        String str2="i love ";
        System.out.println(ret);//Print i love china

        //6.public int length()
        //Get string length
        String str3="we are family";
        System.out.println(str3.length());//Print 13

        //7.public boolean isEmpty()
        //Judge whether it is an empty string, but it is not null, but has a length of 0
        String str4="";

3, StringBuffer and StringBuilder

Any String constant is a String object, and once declared, the String constant cannot be changed. If the object content is changed, only the reference point will be changed.

Generally speaking, the operation of String is relatively simple. However, due to the immutability of String, StringBuffer and StringBuilder classes are provided to facilitate String modification.

ps: most of the functions of StringBuffer and StringBuilder are the same. We mainly use StringBuilder to introduce them here

Use "+" in String to connect strings, but this operation needs to be changed to the append() method in the StringBuffer class:
Code examples are as follows:

public class TestDemo {
    //StringBuffer and StringBuilder
    public static void main(String[] args) {
        StringBuilder sb=new StringBuilder();
        System.out.println(sb.toString());//Print abcdefg
        System.out.println(sb.toString());//Print abcdefg123 and it will change accordingly

        //The ps:append() method can be used together
        StringBuilder sb1=new StringBuilder();
        System.out.println(sb1);//Print 123abc

        //PS: there is a reverse method in stringbuild and StringBuffer, but not String
        //Using this method, the inversion of string can be realized very easily
        System.out.println(sb);//Print 321gfedcba

Note: the String and buffer classes cannot be converted directly. If you want to convert each other, you can use the following principles:
String becomes StringBuffer: use the construction method or append() method of StringBuffer
Change StringBuffer to String: call toString() method.
Code examples are as follows:

//Convert StringBuffer or StringBuilder to String
    public static String func(){
        StringBuffer stringBuffer=new StringBuffer();
        return stringBuffer.toString();

    //Convert String to StringBuffer or StringBuilder
    public static StringBuffer func(String str){
        StringBuffer stringBuffer=new StringBuffer();
        return stringBuffer;


String operation is a very common operation in our future work It is very simple and convenient to use. You must use it skillfully Points to note:
  1. String comparison, the difference between = =, equals, compareTo

  2. Understand string constant pool and experience the idea of "pool"

  3. Understand string immutability

  4. Application scenario of split

  5. Functions of StringBuffer and StringBuilder

Topics: Java string StringBuffer StringBuilder