JavaSE - Detailed explanation of common methods of String class (playing with strings)

ced485cbb11e458d81a746890b32cf3f.gif

Author: Rukawa Maple Knock Code

Blog Homepage: Rukawa Kaede's Blog

Column: Learn java with me

Quote: Stay hungry stay foolish

If you want to do good things, you must first sharpen your tools. Let me introduce you to a super powerful tool for winning offers from big manufacturers - Niuke.com

Click to register for free and brush the questions with me  

Article directory

1. Common construction of strings

2. Comparison of String objects

1. == compares whether it refers to the same object

2. boolean equals(Object anObject) method: compare in lexicographical order

3. int compareTo(String s) method: compare lexicographically

4. int compareToIgnoreCase(String str) method

3. String lookup

char charAt(int index)

int indexOf(int ch)

int indexOf(int ch, int fromIndex)

int indexOf(String str)

int indexOf(String str, int fromIndex)

int lastIndexOf(int ch)

int lastIndexOf(int ch, int fromIndex)

int lastIndexOf(String str)

int lastIndexOf(String str, int fromIndex)

4. Conversion

1. Numerical and string conversion

2. Case conversion

3. String to Array 

4. Formatting

5. String replacement

 1. Replace all specified content

2. Replace the first content

6. String splitting

1. Split all strings 

2. The string is split into limit groups in the specified format

3. "." split

7. String interception

1. Intercept from the specified index to the end

2. Intercept some content

8. String trim()


1. Common construction of strings

1. Use constant construction

2. Construct using newString

3. Use character array construction

public class Test {
    public static void main(String[] args) {
        //1
        String str1 = "hello";
        System.out.println(str1);
        //2
        String str2 = new String("hello");
        System.out.println(str2);
        //3
        char[] chars = {'h','e','l','l','o'};
        System.out.println(chars);
    }
}

 Reference when using other methods: string official documentation 

Strings cannot be inherited , the following is the source code of the String class

 value is an array of char type, the string is actually stored in the array of char type, and there is no /0 at the end of the string

  So String is a reference type and does not store the string itself internally , see an example:

public class Test {
    public static void main(String[] args) {

        String str1 = new String("hello");

        String str2 = new String("world");

        String str3 = str1;
        System.out.println(str3);
    }
}

str1 and str2 refer to different objects str1 and str3 refer to the same object 

public class Test {
    public static void main(String[] args) {

        String str1 = new String("hello");

        String str2 = new String("hello");
        
        System.out.println(str1==str2);

        System.out.println(str1.equals(str2));

    }
}

 Because the String class is a reference type, even if the contents of the strings are the same, they are not equal. To compare whether they are equal, the method must be compared by calling the object.

In Java, "" is also an object of the String class.

public class Test {
    public static void main(String[] args) {
        System.out.println("hello".toString());

    }
}

You can call methods such as toString() 

2. Comparison of String objects

1. == compares whether it refers to the same object

For primitive type variables, the comparison is whether the value stored in the two variables is the same

For reference type variables, the comparison is whether the two reference variables refer to the same object

as mentioned above

2. boolean equals(Object anObject) method: compare in lexicographical order

lexicographical order: the order of character sizes

 The String class overrides the equals method in the parent class Object, and the equals in Object is compared by == by default.

The comparison logic after rewriting:

 public boolean equals(Object anObject) {

        //1. 先检测this和anObject是否为同一个对象比较,如果是返回true

        if (this == anObject) {
            return true;
        }

        //2. 检测anObject是否为String类型的对象,如果是继续比较,否则返回false

        if (anObject instanceof String) {

            //向下转型

            String anotherString = (String)anObject;
            int n = value.length;

        //3. this和anObject两个字符串的长度是否相同,是继续比较,否则返回false

            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;

                //4. 按照字典序,从前往后逐个字符进行比较

                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

3. int compareTo(String s) method: compare lexicographically

equals returns a boolean type, while compareTo returns an int type

How to compare:

1. First compare the size according to the dictionary order, if there are unequal characters, directly return the size difference between the two characters

2. If the first k characters are equal (k is the minimum length of two characters), the return value is the difference between the lengths of the two strings

See an example: 

public class Test {
    public static void main(String[] args) {

        String str1 = new String("hello");

        String str2 = new String("hello");

        int ret = str1.compareTo(str2);
        if(ret>0){
            System.out.println("str1>str2");
        } else if (ret==0) {
            System.out.println("str1=str2");
        }
        else {
            System.out.println("str1<str2");
        }

    }

}

 Source code:

public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }

4. int compareToIgnoreCase(String str) method

Same as compareTo, but ignore case comparison 

public class Test {
    public static void main(String[] args) {

        String s1 = new String("abc");
        String s2 = new String("ac");
        String s3 = new String("ABc");
        String s4 = new String("abcdef");
        System.out.println(s1.compareToIgnoreCase(s2)); //不同输出字符差值-1
        System.out.println(s1.compareToIgnoreCase(s3)); //相同输出0
        System.out.println(s1.compareToIgnoreCase(s4)); //前k个字符完全相同,输出长度差值-3
        
    }
}

3. String lookup

Common search methods provided by the String class:

char charAt(int index)

Returns the character at the index position. If the index is negative or out of bounds, an IndexOutOfBoundsException is thrown

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdef");
        for (int i= 0;  i< s1.length(); i++) {
            System.out.println(s1.charAt(i));
        }
    }
}

 int indexOf(int ch)

Returns the position of the first occurrence of ch, does not return -1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdef");

        System.out.println(s1.indexOf('c'));
    }
}

int indexOf(int ch, int fromIndex)

Start from the fromIndex position to find the position where ch appears for the first time, and does not return -1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.indexOf('c',3));
    }
}

int indexOf(String str)

Returns the position of the first occurrence of str, does not return -1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.indexOf("cde"));
    }
}

int indexOf(String str, int fromIndex)

Start from the fromIndex position to find the position where str appears for the first time, without returning -1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.indexOf("cde",3));
    }
}

int lastIndexOf(int ch)

Search from the back to the front, return the position where ch appears for the first time, and not return -1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("c"));
    }
}

int lastIndexOf(int ch, int fromIndex)

Starting from the fromIndex position, looking for the position where ch appears for the first time from the back to the front, it does not return -1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("c",4));
    }
}

int lastIndexOf(String str)

Search from the back to the front, return the position of the first occurrence of str, do not return -1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("abc"));
    }
}

int lastIndexOf(String str, int fromIndex)

Start from the fromIndex position, look for the position where str first appears from the back to the front, and does not return -1

public class Test {
    public static void main(String[] args) {
        String s1 = new String("abcdecf");

        System.out.println(s1.lastIndexOf("abc",4));
    }
}

4. Conversion

1. Numerical and string conversion

public class Test {
    public static void main(String[] args) {
        String s1 = String.valueOf(123);

        System.out.println(s1);
    }
}

 

 You can see that there are many overloaded methods for us to use, which can convert many different types of values ​​to strings

2. Case conversion

toUpperCase()

toLowerCase()

public class Test {
    public static void main(String[] args) {
        String s1 = "hellO嗨";
        String ret = s1.toUpperCase();
        System.out.println(ret);
    }
}

toUpperCase() will only convert lowercase to uppercase, nothing else will change, so does toLowerCase()

3. String to Array 

toCharArray()

public class Test {
    public static void main(String[] args) {
        String str1 = "abcdef";
        char[] chars = str1.toCharArray();
        System.out.println(Arrays.toString(chars));
    }
}

 array to string

public class Test {
    public static void main(String[] args) {

        char[] chars = {'h','e','l','l','o'};
        String s1 = new String(chars);
        System.out.println(s1);
    }
}

4. Formatting

String.format()

public class Test {
    public static void main(String[] args) {

        String s = String.format("%d-%d-%d",2022,8,14);
        System.out.println(s);
    }
}

5. String replacement

Note: Since strings are immutable objects, replacement does not modify the current string, but produces a new string

Use a string to replace the existing string data, method:

1.String replaceAll(String regex, String replacement) 

2.String replaceFirst(String regex, String replacement)

 1. Replace all specified content

public class Test {
    public static void main(String[] args) {

        String s = "abcadeafagf";
        String ret = s.replaceAll("a","c");
        System.out.println(s);
        System.out.println(ret);
    }
}

 

 It can be seen that the original string is unchanged after the replacement string, and a new string is required to receive after the replacement.

2. Replace the first content


public class Test {
    public static void main(String[] args) {

        String s = "abcadeafagf";
        String ret = s.replaceFirst("a","c");
        System.out.println(s);
        System.out.println(ret);
    }
}

6. String splitting

Divide a complete string into several substrings according to the specified delimiter

String[] split(String regex)

String[] split(String regex, int limit)

1. Split all strings 

public class Test {
    public static void main(String[] args) {

        String s = "hello world hello";
        String[] ret = s.split(" ");
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

2. The string is split into limit groups in the specified format

public class Test {
    public static void main(String[] args) {

        String s = "hello world hello";
        String[] ret = s.split(" ",2);
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

3. "." split

public class Test {
    public static void main(String[] args) {

        String s = "hello.world.hello";
        String[] ret = s.split(".");
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

 Normal use split(".") to split, we found that the print array is empty, indicating that the split was not successful

Reason: "." needs to be escaped, after adding "\\.", it can be split

public class Test {
    public static void main(String[] args) {

        String s = "hello.world.hello";
        String[] ret = s.split("\\.");
        System.out.println(s);
        System.out.println(Arrays.toString(ret));
    }
}

Summarize:

1. The characters "|", "*", "+" must be escaped, preceded by "\\"

2. If it is "\", then it must be written as "\\\\"

3. If there are multiple separators in a string, you can use "|" as a hyphen, that is, s.split("=|&"); is to split the s string by = and &

7. String interception

String substring(int beginIndex)

String substring(int beginIndex, int endIndex)

1. Intercept from the specified index to the end

public class Test {
    public static void main(String[] args) {

        String s = "hello world";
        String ret = s.substring(5);
        System.out.println(s);
        System.out.println(ret);
    }
}

2. Intercept some content

public class Test {
    public static void main(String[] args) {

        String s = "hello world";
        String ret = s.substring(0,5);
        System.out.println(s);
        System.out.println(ret);
    }
}

 Summarize:

1. The index starts from 0

2. Pay attention to the writing method of the front-closed and back-open interval, substring(0, 5) means the character with subscript 0, excluding the subscript 5

8. String trim()

Function: remove the left and right spaces in the string, keep the middle spaces

public class Test {
    public static void main(String[] args) {

        String s = "   hello world    ";
        String ret = s.trim();
        System.out.println(s);
        System.out.println(ret);
    }
}

 Summarize:

We noticed that most of the String class methods do not directly manipulate the original string, but return a new string

"The sharing of this issue is here, remember to give the blogger a three-link, your support is the biggest driving force for my creation!

ced485cbb11e458d81a746890b32cf3f.gif

Guess you like

Origin blog.csdn.net/chenchenchencl/article/details/126330055