String (there is a small problem)

The String class provides a variety of methods to search for and extract substrings. Commonly used methods are:

// 是否包含子串:
"Hello".contains("ll"); // true

Search substring

example:

"Hello".indexOf("l"); // 2
"Hello".lastIndexOf("l"); // 3
"Hello".startsWith("He"); // true
"Hello".endsWith("lo"); // true

Extract substring

example:

"Hello".substring(2); // "llo"
"Hello".substring(2, 4); "ll"

Replace substring

To replace a substring in a string, there are two methods. One is based on character or string replacement:

String s = "hello";
s.replace('l', 'w'); // "hewwo",所有字符'l'被替换为'w'
s.replace("ll", "~~");  //  "he~~o",所有子串"ll"被替换为"~~" 

Split string

To split a string, use the split() method, and the regular expression is also passed in:

String s = "A,B,C,D";
String[] ss = s.split("\\,"); // {"A", "B", "C", "D"}

Concatenated string

To concatenate strings, use the static method join(), which connects the string array with the specified string:

String[] arr = {
    
    "A", "B", "C"};
String s = String.join("***", arr); // "A***B***C"

Format string

The string provides the formatted() method and the format() static method. You can pass in other parameters, replace the placeholders, and then generate a new string:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        String s = "Hi %s, your score is %d!";
        System.out.println(s.formatted("Alice", 80));
        System.out.println(String.format("Hi %s, your score is %.2f!", "Bob", 59.5));
    }
}

There are several placeholders, and several parameters are passed in later. The parameter type should be consistent with the placeholder. We often use this method to format information. Commonly used placeholders are:

%s: display string;
%d: display integer;
%x: display hexadecimal integer;
%f: display floating point number.

Placeholders can also be formatted, for example: %.2f means to display two decimal places. If you are not sure what placeholder to use, always use %s, because %s can display any data type.

Type conversion

To convert any basic type or reference type to a string, you can use the static method valueOf() . This is an overloaded method, the compiler will automatically select the appropriate method according to the parameters:

String.valueOf(123); // "123"
String.valueOf(45.67); // "45.67"
String.valueOf(true); // "true"
String.valueOf(new Object()); // 类似java.lang.Object@636be97c

To convert a string to other types, it needs to be based on the situation. For example, to convert a string to int type:

int n1 = Integer.parseInt("123"); // 123
int n2 = Integer.parseInt("ff", 16); // 按十六进制转换,255

Convert the string to boolean type:

boolean b1 = Boolean.parseBoolean("true"); // true
boolean b2 = Boolean.parseBoolean("FALSE"); // false

Pay special attention to the fact that Integer has a getInteger(String) method, which does not convert a string to an int, but converts the system variable corresponding to the string to an Integer:

Integer.getInteger("java.version"); // 版本号,11

Convert between String and char

char[] cs = "Hello".toCharArray(); // String -> char[]
String s = new String(cs); // char[] -> String

If the char[] array is modified, String will not change:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        char[] cs = "Hello".toCharArray();
        String s = new String(cs);
        System.out.println(s);
        cs[0] = 'X';
        System.out.println(s);
    }
}

Both results are:
Hello
Hello

This is because when a new String instance is created through new String(char[]), it will not directly reference the passed char[] array, but will make a copy. Therefore, modifying the external char[] array will not Affects the char[] array inside the String instance, because these are two different arrays.

It can be seen from the immutability design of String that if the incoming object is likely to change, we need to copy it instead of directly referencing it.

For example, the following code designs a Score class to store the scores of a group of students:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int[] scores = new int[] {
    
     88, 77, 51, 66 };
        Score s = new Score(scores);
        s.printScores();
        scores[2] = 99;
        s.printScores();
    }
}

class Score {
    
    
    private int[] scores;
    public Score(int[] scores) {
    
    
        this.scores = scores;
    }

    public void printScores() {
    
    
        System.out.println(Arrays.toString(scores));
    }
}

[88, 77, 51, 66]
[88, 77, 99, 66]

Observing the output twice, because Score directly references the externally passed int[] array, this will cause the external code to modify the int[] array and affect the fields of the Score class. If the external code is not trustworthy, this will cause security risks.

Please fix the construction method of Score so that the modification of the array by external code does not affect the int[] field of the Score instance.

Guess you like

Origin blog.csdn.net/Mr_zhang66/article/details/113243112