Common class library - String class

String class

String overview

​ 1. String class in Java Lang package, so there is no need to guide the package when using

​ 2 the String class represents a String. All String literals (such as "abc") in the Java program are implemented as instances of this class, 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

Construction method of String class

Common construction methods

Sample code

package com.itheima.string;

public class Demo2StringConstructor {
    /*
        String Common construction methods of class:

            public String() : Create a blank string object that contains nothing
            public String(char[] chs) : Create a string object based on the contents of the character array
            public String(String original) : Create a string object based on the passed in string content
            String s = "abc";  Create a string object by direct assignment. The content is abc

         be careful:
                String This class is special. When printing its object name, there will be no memory address
                It is the real content recorded by the object

                Object oriented - inheritance, object class
     */
    public static void main(String[] args) {
        // public String(): create a blank string object without any content
        String s1 = new String();
        System.out.println(s1);

        // public String(char[] chs): creates a string object according to the contents of the character array
        char[] chs = {'a','b','c'};
        String s2 = new String(chs);
        System.out.println(s2);

        // public String(String original): creates a string object based on the incoming string content
        String s3 = new String("123");
        System.out.println(s3);
    }
}

Create a comparison of the differences between string objects

  • Created by construction method

    ​ 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

  • Create by direct assignment

    ​ 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 maintain it in the String pool

String comparison

String comparison

  • ==Compare basic data types: specific values are compared
  • ==Compare reference data types: object address values are compared

String class: public boolean equals(String s) compares whether the contents of two strings are the same and case sensitive

code:

package com.itheima.stringmethod;

public class Demo1Equals {
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "ABC";
        String s3 = "abc";

        // equals: compare string contents, case sensitive
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));

        // equalsIgnoreCase: compare string contents, ignoring case
        System.out.println(s1.equalsIgnoreCase(s2));
    }
}

User login case [application]

Case requirements:

​ Given the user name and password, please use the program to simulate user login. Give a total of three opportunities. After logging in, give corresponding prompts

Implementation steps:

  1. Given the user name and password, define two string representations
  2. Enter the user name and password to log in with the keyboard, which is implemented with Scanner
  3. Compare the user name and password entered on the keyboard with the known user name and password, and give the corresponding prompt.
  4. The content comparison of the string is realized by the equals() method
  5. Use the loop to realize multiple opportunities. The number of times here is clear. Use the for loop to realize it. When the login is successful, use break to end the loop

Code implementation:

package com.itheima.test;

import java.util.Scanner;

public class Test1 {
    /*
        Requirements: given the user name and password, please use the program to simulate user login.
              Give a total of three opportunities. After logging in, give corresponding prompts

        Idea:
        1. Given the user name and password, define two string representations
        2. Enter the user name and password to log in with the keyboard, which is implemented with Scanner
        3. Compare the user name and password entered on the keyboard with the known user name and password, and give the corresponding prompt.
            The content comparison of the string is realized by the equals() method
        4. Use the loop to realize multiple opportunities. The number of times here is clear. Use the for loop to realize it. When the login is successful, use break to end the loop

     */
    public static void main(String[] args) {
        // 1. If the user name and password are known, define two string representations
        String username = "admin";
        String password = "123456";
        // 2. Enter the user name and password to log in with the keyboard, which is implemented with Scanner
        Scanner sc = new Scanner(System.in);
        // 4. Use the loop to realize multiple opportunities. The number of times here is clear, and use the for loop to realize
        for(int i = 1; i <= 3; i++){
            System.out.println("enter one user name:");
            String scUsername = sc.nextLine();
            System.out.println("Please input a password:");
            String scPassword = sc.nextLine();
            // 3. Compare the user name and password entered on the keyboard with the known user name and password and give the corresponding prompt.
            if(username.equals(scUsername) && password.equals(scPassword)){
                System.out.println("Login successful");
                break;
            }else{
                if(i == 3){
                    System.out.println("Your login times have reached today's limit, Please come back tomorrow");
                }else{
                    System.out.println("Login failed,You still have" + (3-i) +"Second chance");
                }

            }
        }

    }
}

Traversal string case [application]

Case requirements:

​ Enter a string on the keyboard and use the program to traverse the string on the console

Implementation steps:

  1. Keyboard input a string, using Scanner to achieve
  2. To traverse a string, you must first be able to obtain each character in the string. public char charAt(int index): returns the char value at the specified index. The index of the string also starts from 0
  3. Traverse the string, and then get the length of the string. public int length(): return the length of this string
  4. Traversal printing

Code implementation:

package com.itheima.test;

import java.util.Scanner;

public class Test2 {
    /*
        Requirements: enter a string on the keyboard and use the program to traverse the string on the console

        Idea:
        1. Keyboard input a string, using Scanner to achieve
        2. To traverse a string, you must first be able to get each character in the string
            public char charAt(int index): Returns the char value at the specified index, and the index of the string starts from 0
        3. Traverse the string, and then get the length of the string
            public int length(): Returns the length of this string
        4. Traversal printing
9
     */
    public static void main(String[] args) {
        //  1. Enter a string on the keyboard and use Scanner to realize it
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter:");
        String s = sc.nextLine();
        // 2. To traverse a string, you must first be able to get each character in the string
        for(int i = 0; i < s.length(); i++){
            // i: each index of the string
            char c = s.charAt(i);
            System.out.println(c);
        }
    }
}

Case of counting the number of characters [application]

Case requirements:

​ Enter a string on the keyboard and use the program to traverse the string on the console

Implementation steps:

  1. Keyboard input a string, using Scanner to achieve
  2. Split the string into character array, public char[] toCharArray(): split the current string into character array and return
  3. Number of traversal characters

Code implementation:

package com.itheima.test;

import java.util.Scanner;

public class Test3 {
    /*
       Requirements: enter a string on the keyboard and use the program to traverse the string on the console

       Idea:
       1. Keyboard input a string, using Scanner to achieve
       2. Splits a string into an array of characters
                public char[] toCharArray( ): Splits the current string into an array of characters and returns
       3. Traversal character array

    */
    public static void main(String[] args) {
        //  1. Enter a string on the keyboard and use Scanner to realize it
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter:");
        String s = sc.nextLine();
        // 2. Split the string into character arrays
        char[] chars = s.toCharArray();
        // 3. Traverse character array
        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);
        }
    }
}

Mobile phone number screening - string interception

Case requirements:

​ Accept a mobile phone number from the keyboard in the form of string and shield the middle four numbers
The final effect is: 156 * * * * 1234

Implementation steps:

  1. Keyboard input a string, using Scanner to achieve
  2. Intercept the first three digits of the string
  3. Intercept the last four digits of the string
  4. Splice the two intercepted strings with * * * * in the middle to output the result

Code implementation:

package com.itheima.test;

import java.util.Scanner;

public class Test5 {
    /*
        Requirements: accept a mobile phone number from the keyboard in the form of string, and shield the middle four numbers
        Final effect: 123156 * * *

        Idea:
        1. Keyboard input a string, using Scanner to achieve
        2. Intercept the first three digits of the string
        3. Intercept the last four digits of the string
        4. Splice the two intercepted strings with * * * * in the middle to output the result

     */
    public static void main(String[] args) {
        // 1. Enter a string on the keyboard and use Scanner to realize it
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter your mobile number:");
        String telString = sc.nextLine();
        // 2. Intercept the first three digits of the string
        String start = telString.substring(0,3);
        // 3. Intercept the last four digits of the string
        String end = telString.substring(7);
        // 4. Splice the two intercepted strings with * * * * in the middle to output the result
        System.out.println(start + "****" + end);
    }
}

Sensitive word replacement - string replacement

Case requirements:

​ Enter a string on the keyboard. If the string contains (TMD), use * * * instead

Implementation steps:

  1. Keyboard input a string, using Scanner to achieve
  2. Replace sensitive words
    String replace(CharSequence target, CharSequence replacement)
    Replace the target content in the current string with replacement to return a new string
  3. Output results

Code implementation:

package com.itheima.test;

import java.util.Scanner;

public class Test6 {
    /*
        Requirement: enter a string with the keyboard. If the string contains (TMD), use * * * instead

        Idea:
        1. Keyboard input a string, using Scanner to achieve
        2. Replace sensitive words
                String replace(CharSequence target, CharSequence replacement)
                Replace the target content in the current string with replacement to return a new string
        3. Output results

     */
    public static void main(String[] args) {
        // 1. Enter a string on the keyboard and use Scanner to realize it
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter:");
        String s = sc.nextLine();
        // 2. Replace sensitive words
        String result = s.replace("TMD","***");
        // 3. Output results
        System.out.println(result);
    }
}

Cut string

Case requirements:

​ Input student information from the keyboard in the form of string, for example: "Zhang San, 23"

​ Cut the valid data from the string and encapsulate it as a Student object

Implementation steps:

  1. Write the Student class to encapsulate the data

  2. Keyboard input a string, using Scanner to achieve

  3. Cut the string according to the comma to get (Zhang San) (23)

    String[] split(String regex): cut according to the incoming string as a rule
    Store the cut content into the string array and return the string array

  4. Take the element content from the obtained string array and encapsulate it as an object through the parametric construction method of Student class

  5. Call the getXxx method of the object, take out the data and print it.

Code implementation:

package com.itheima.test;

import com.itheima.domain.Student;

import java.util.Scanner;

public class Test7 {
    /*
         Requirement: input student information from the keyboard in the form of string, for example: "Zhang San, 23"
                Cut the valid data from the string and encapsulate it as a Student object
         Idea:
            1. Write the Student class to encapsulate the data
            2. Keyboard input a string, using Scanner to achieve
            3. Cut the string according to the comma to get (Zhang San) (23)
                    String[] split(String regex) : Cut according to the incoming string as a rule
                    Store the cut content into the string array and return the string array
            4. Take the element content from the obtained string array and encapsulate it as an object through the parametric construction method of Student class
            5. Call the getXxx method of the object, take out the data and print it.

     */
    public static void main(String[] args) {
        // 2. Enter a string on the keyboard and use Scanner to realize it
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter student information:");
        String stuInfo = sc.nextLine();
        // stuInfo = "Zhang San, 23";
        // 3. Cut the string according to the comma to get (Zhang San) (23)
        String[] sArr = stuInfo.split(",");

//        System.out.println(sArr[0]);
//        System.out.println(sArr[1]);

        // 4. Take out the element content from the obtained string array and encapsulate it as an object through the parametric construction method of Student class
        Student stu = new Student(sArr[0],sArr[1]);

        // 5. Call the getXxx method of the object, take out the data and print it.
        System.out.println(stu.getName() + "..." + stu.getAge());
    }
}

Summary of String method

Common methods of String class:

​ public boolean equals(Object anObject) compares the contents of strings and is strictly case sensitive

​ Public Boolean equalsignorecase (string otherstring) compares the contents of strings, ignoring case

​ public int length() returns the length of this string

​ Returns the value of public char at the specified index

​ public char[] toCharArray() splits the string into character arrays and returns

​ public String substring(int beginIndex, int endIndex) intercepts according to the start and end indexes to get a new string (including header and not tail)

​ public String substring(int beginIndex) is intercepted from the incoming index to the end to get a new string

​ public String replace(CharSequence target, CharSequence replacement) uses the new value to replace the old value in the string to get a new string

​ public String[] split(String regex) cuts the string according to the incoming rules to get the string array

StringBuilder class

StringBuilder class overview

​ Overview: StringBuilder is a variable string class. We can regard it as a container. The variable here means that the content in the StringBuilder object is variable

The difference between StringBuilder class and String class

  • String class: the content is immutable
  • StringBuilder class: the content is mutable

Construction method of StringBuilder class

Common construction methods

Method name explain
public StringBuilder() Create a blank variable string object that contains nothing
public StringBuilder(String str) Create a variable string object based on the content of the string

Sample code

public class StringBuilderDemo01 {
    public static void main(String[] args) {
        //public StringBuilder(): create a blank variable string object without any content
        StringBuilder sb = new StringBuilder();
        System.out.println("sb:" + sb);
        System.out.println("sb.length():" + sb.length());

        //public StringBuilder(String str): creates a variable string object according to the contents of the string
        StringBuilder sb2 = new StringBuilder("hello");
        System.out.println("sb2:" + sb2);
        System.out.println("sb2.length():" + sb2.length());
    }
}

Member methods commonly used by StringBuilder

  • Add and reverse methods

    Method name explain
    Public StringBuilder append (any type) Add data and return the object itself
    public StringBuilder reverse() Returns the opposite sequence of characters
  • Sample code

public class StringBuilderDemo01 {
    public static void main(String[] args) {
        //create object
        StringBuilder sb = new StringBuilder();

        //Public StringBuilder append (any type): add data and return the object itself
//        StringBuilder sb2 = sb.append("hello");
//
//        System.out.println("sb:" + sb);
//        System.out.println("sb2:" + sb2);
//        System.out.println(sb == sb2);

//        sb.append("hello");
//        sb.append("world");
//        sb.append("java");
//        sb.append(100);

        //Chain programming
        sb.append("hello").append("world").append("java").append(100);

        System.out.println("sb:" + sb);

        //public StringBuilder reverse(): returns the opposite character sequence
        sb.reverse();
        System.out.println("sb:" + sb);
    }
}

Conversion between StringBuilder and String [application]

  • Convert StringBuilder to String

    public String toString(): you can convert StringBuilder to String through toString()

  • Convert String to StringBuilder

    public StringBuilder(String s): you can convert a String into a StringBuilder by constructing a method

  • Sample code

public class StringBuilderDemo02 {
    public static void main(String[] args) {
        /*
        //StringBuilder Convert to String
        StringBuilder sb = new StringBuilder();
        sb.append("hello");

        //String s = sb; //This is the wrong approach

        //public String toString(): Tobuilder can convert toString() to String()
        String s = sb.toString();
        System.out.println(s);
        */

        //Convert String to StringBuilder
        String s = "hello";

        //StringBuilder sb = s; // This is the wrong approach

        //public StringBuilder(String s): you can convert a String into a StringBuilder by constructing a method
        StringBuilder sb = new StringBuilder(s);

        System.out.println(sb);
    }
}

StringBuilder splicing string case

Case requirements:

​ Define a method, splice the data in the int array into a string according to the specified format, return, and call this method,

​ And output the results on the console. For example, the array is int[] arr = {1,2,3}, The output result after executing the method is: [1, 2, 3]

Implementation steps:

  1. Define an array of type int, and use static initialization to complete the initialization of array elements
  2. Define a method to splice the data in the int array into a string according to the specified format and return it.
    Return value type String, parameter list int[] arr
  3. In the method, use StringBuilder to splice according to the requirements, and turn the result into String to return
  4. Call the method and receive the result with a variable
  5. Output results

Code implementation:

/*
    Idea:
        1:Define an array of type int, and use static initialization to complete the initialization of array elements
        2:Define a method to splice the data in the int array into a string according to the specified format and return it.
          Return value type String, parameter list int[] arr
        3:In the method, use StringBuilder to splice according to the requirements, and turn the result into String to return
        4:Call the method and receive the result with a variable
        5:Output results
 */
public class StringBuilderTest01 {
    public static void main(String[] args) {
        //Define an array of type int, and use static initialization to complete the initialization of array elements
        int[] arr = {1, 2, 3};

        //Call the method and receive the result with a variable
        String s = arrayToString(arr);

        //Output results
        System.out.println("s:" + s);

    }

    //Define a method to splice the data in the int array into a string according to the specified format and return
    /*
        Two clear:
            Return value type: String
            Parameter: int[] arr
     */
    public static String arrayToString(int[] arr) {
        //In the method, use StringBuilder to splice according to the requirements, and turn the result into String to return
        StringBuilder sb = new StringBuilder();

        sb.append("[");

        for(int i=0; i<arr.length; i++) {
            if(i == arr.length-1) {
                sb.append(arr[i]);
            } else {
                sb.append(arr[i]).append(", ");
            }
        }

        sb.append("]");

        String s = sb.toString();

        return  s;
    }
}

Tags: Java

Posted by znouza on Tue, 24 May 2022 04:49:14 +0300