Java String class (1)

Importance of the String class

We have already involved strings in C language before, but to represent strings in C language, we can only use character arrays or character pointers. We can use the string series functions provided by the standard library to complete most of the operations, but this will The separation of data and methods of manipulating data does not conform to the object-oriented thinking , and strings are widely used, so the Java language specifically provides the String class.

And in the current development and school recruitment written test, the String class is even more important, so let us look at the String class today.

common method

string construction

There are many construction methods provided in the String class, and the following three are commonly used:

 public static void main(String[] args) {
        //使用常量字符串构造
        String s1 = "hello world";
        System.out.println(s1);

        //直接newString对象
        String s2 = new String("hello world");
        System.out.println(s2);

        //使用字符数组进行构造
        char[] array = {'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'};
        String s3 = new String(array);
        System.out.println(s3);
    }

Notice:

1. String is a reference type, and the string itself is not stored internally. In the implementation source code of the String class, the instance variables of the String class are as follows:

 We can see that String has two main members: value[], hash.

hash: In Java, Stringthe in the class hashis hashCode()calculated by the method, and hashCode()the method is calculated based on the content of the string. When you call hashCode()the method, you actually calculate a hash code value based on the character content of the string . General hash defaults to 0

value[]: In Java, Stringin the class value[]is a character array, which stores the character content of the string. Each Stringobject has an value[]array to store the characters of the string, this array is private final char[]of type .

public static void main(String[] args) {
        //s1和s2引用的是不同的对象 s1和s3引用的是不同对象
        String s1 = new String("hello");
        String s2 = new String("world");
        String s3 = s1;
        String s4 = "";//表明指向的对象是空的
        String s5 = null;//表明不指向任何对象

        System.out.println(s1.length());//获取字符串的长度-输出5
        //isEmpyt():检查字符串是否是空,如果是空返回true,不是空返回false
        System.out.println(s1.isEmpty());//false
        System.out.println(s4.isEmpty());//true
        System.out.println(s5.isEmpty());//空指针异常
    }

2. In Java, "" is also an object of type String .

Comparison of String objects

String comparison is also one of the common operations, such as: string sorting. Java provides 4 ways:

1. == compares whether the references are the same object .

Note: For built-in types (basic types such as int, etc.), == compares the value in the variable; for reference types, == compares the address in the reference.

public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = 10;

        //对于基本类型变量,==比较的是两个变量中存储的值是否相同
        System.out.println(a == b);//false
        System.out.println(a == c);//true

        //对于引用类型变量,==比较的是两个引用变量引用的是否为同一个对象
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = new String("world");
        String s4 = s1;
        System.out.println(s1 == s2);//false
        System.out.println(s2 == s3);//false
        System.out.println(s1 == s4);//true
    }

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

Lexicographic order: order of character size

The String class rewrites the equals method in the parent class Object. The equals in Object defaults to == comparison. After String rewrites the equals method, it compares according to the following rules: for example, s1.equals(s2)

public boolean equals(Object anObject) {
    // 1. 先检测this 和 anObject 是否为同一个对象比较,如果是返回true
    if (this == anObject) {
        return true;
    } 

    // 2. 检测anObject是否为String类型的对象,如果是继续比较,否则返回false
    if (anObject instanceof String) {
        // 将anObject向下转型为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;
}

Give an example of usage:

 public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = new String("Hello");

        //s1,s2,s3引用的是三个不同的对象,因此==比较全部为false
        System.out.println(s1 == s2);//false
        System.out.println(s1 == s3);//false

        //equals比较:String对象中的逐个字符
        //虽然s1和s2引用的是不同的对象,但是两个对象中放置的内容相同
        //s1和s3引用的是不同的对象,而且两个对象中的内容也不同
        System.out.println(s1.equals(s2));//true
        System.out.println(s1.equals(s3));//false
    }

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

Unlike equals, equals returns a boolean type, while compareTo returns an int type. Specific comparison method:

1. First compare the sizes in 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 two strings

  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.compareTo(s2));//不同输出字符差值-1
        System.out.println(s1.compareTo(s3));//相同输出0
        System.out.println(s1.compareTo(s4));//前k个字符完全相同,返回长度差值-3
    }

4.int compareTolgnoreCase(String str) method: same as compareTo method, but case comparison is ignored

string lookup

String search is also a very common operation on strings, and the String class provides common search methods:

method Function
char charAt(int index)

Return the character at the index position, if the index is negative or out of bounds, throw

IndexOutOfBoundsException exception

int indexOf(int ch) Returns the position of the first occurrence of ch, or -1 if there is no
int indexOf(int ch, int fromIndex) Find the first occurrence of ch from the fromIndex position
int IndexOf(String str)

Returns the position of the first occurrence of str, or -1 if there is no

int IndexOf(String str, int fromIndex) Find the first occurrence of str from the fromIndex position, and return -1
int lastIndexOf(int ch)

Search from the back to the front, return the position where ch first appeared, and return -1 if not

int lastIndexOf(String str) Search from the back to the front, return the first occurrence of str, not return -1
int lastIndexOf(int ch, int fromIndex) Find the first occurrence of ch from the back to the front from the fromIndex position, and return -1 if it does not return
int lastIndexOf(String str,int fromIndex) Starting from the fromIndex position, find the first occurrence of str from the back to the front, and return -1

Let's take a string as an example:

 public static void main(String[] args) {
        String s = "aaabbbcccaaabbbccc";
        System.out.println(s.charAt(3));//'b
        System.out.println(s.indexOf('d'));//-1
        System.out.println(s.indexOf('c'));//6
        System.out.println(s.indexOf('c', 10));//15
        System.out.println(s.indexOf("bbb"));//3
        System.out.println(s.indexOf("bbb", 10));//12
        System.out.println(s.lastIndexOf('c'));//17
        System.out.println(s.lastIndexOf('c', 10));//8
        System.out.println(s.lastIndexOf("bbb"));//12
        System.out.println(s.lastIndexOf("bbb", 10));//3
    }

convert

1. Conversion of numeric values ​​and strings

public static void main(String[] args) {
        //数值转字符串
        String s1 = String.valueOf(1234);
        String s2 = String.valueOf(12.34);
        String s3 = String.valueOf(true);
        String s4 = String.valueOf(new Student("zhangsan", 18));
        //打印
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);//打印的是对象名@哈希码
        System.out.println("======================");
        //字符串转数字
        //注意:Integer,Double等是Java的包装类型,这个后面会讲
        int data1 = Integer.parseInt("1234");
        double data2 = Double.parseDouble("12.34");
        System.out.println(data1);
        System.out.println(data2);
    }

2. Case conversion

 public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO";
        //注意:不是在原来的基础上转变,转变之后是一个新的对象
        //小写转大写
        System.out.println(s1.toUpperCase());//HELLO
        System.out.println(s2.toLowerCase());//hello

    }

3. String to array

public static void main(String[] args) {
        String s = "hello";
        //字符串转数组
        char[] ch = s.toCharArray();
        for(int i=0; i<ch.length; i++) {
            System.out.print(ch[i]);
        }
        System.out.println();
        //数组转字符串
        String s2 = new String(ch);
        System.out.println(s2);
    }

4. Formatting

public static void main(String[] args) {
        String s = String.format("%d-%d-%d", 2019, 9, 14);
        System.out.println(s);
    }

string replacement

Use a new string to replace the data of the existing string, the available methods are as follows:

method Function
String replaceAll(String regex, String replacement) Replace all specified content
String replaceFirst(String regex, String replacement) Replace first content
String replace(String target,  String replacement) Replace all target strings with the specified string
String replace(char oldChar,  char newChar) Replace all old characters with new ones

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

Guess you like

Origin blog.csdn.net/asdssadddd/article/details/132613392