day08 [common API&String class & StringBuilder class]

1.API

1.1 API Overview - use of help documents

  • What is an API

    API (Application Programming Interface): application programming interface

  • API in Java

    It refers to Java classes with various functions provided in the JDK. These classes encapsulate the underlying implementation. We don't need to care about how these classes are implemented. We just need to learn how to use these classes. We can learn how to use these API s through help documents.

How to use API help documentation:

  • Open help document

  • Locate the input box in the index tab

  • Enter Random in the input box

  • See which package the class is in

  • Look at the description of the class

  • Look at the construction method

  • Look at member methods

1.2 keyboard input string

Scanner class:

next(): if a space is encountered, no more data will be entered. End tag: space, tab

nextLine(): the data can be received completely, and the end mark is carriage return line feed

Code implementation:

package com.itheima.api;

import java.util.Scanner;

public class Demo1Scanner {
    /*
        next() : If you encounter a space, you will no longer enter data

                End tag: space, tab

        nextLine() : The data can be received completely

                End tag: carriage return line feed
     */
    public static void main(String[] args) {
        // 1. Create Scanner object
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter:");
        // 2. Call the nextLine method to receive the string
        // ctrl + alt + v: return value of quick generation method
        String s = sc.nextLine();

        System.out.println(s);
    }
}

package com.itheima.api;

import java.util.Scanner;

public class Demo2Scanner {
    /*
        nextInt When used in conjunction with the nextLine method, the nextLine method has no chance of keyboard entry

        Suggestion: when entering data on the keyboard in the future, if the string and integer are accepted together, it is recommended to use the next method to accept the string
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("please enter an integer:");
        int num = sc.nextInt(); // 10 + enter line feed
        System.out.println("Please enter a string:");
        String s = sc.nextLine();


        System.out.println(num);
        System.out.println(s);
    }
}

2. String class

2.1 String overview

1 the string class is under the java.lang package, so there is no need to import the package when using it

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

2.2 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) : Creates 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);
    }
}

2.4 comparison of differences in creating string objects

  • Create 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 of the String given in the form of "=" 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

2.5 string comparison

2.5.1 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: compares string contents, case sensitive
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));

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

2.6 user login case [application]

Case requirements:

Known 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. If the user name and password are known, 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 implemented with 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 the break to end the loop

Code implementation:

package com.itheima.test;

import java.util.Scanner;

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

        Idea:
        1. If the user name and password are known, 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 implemented with 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 succeeded");
                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");
                }

            }
        }

    }
}

2.7 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. Enter a string on the keyboard and implement it with Scanner
  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(): returns the length of the 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. Enter a string on the keyboard and implement it with Scanner
        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 implement it with Scanner
        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);
        }
    }
}

2.8 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. Enter a string on the keyboard and implement it with Scanner
  2. Split the string into character arrays, public char[] toCharArray(): split the current string into character arrays 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. Enter a string on the keyboard and implement it with Scanner
       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 implement it with Scanner
        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]);
        }
    }
}

2.9 mobile phone number shielding - 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. Enter a string on the keyboard and implement it with Scanner
  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 {
    /*
        Requirement: 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

        Idea:
        1. Enter a string on the keyboard and implement it with Scanner
        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 implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter your mobile phone 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);
    }
}

2.10 sensitive word substitution - string substitution

Case requirements:

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

Implementation steps:

  1. Enter a string on the keyboard and implement it with Scanner
  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 on the keyboard. If the string contains (TMD), use * * * instead

        Idea:
        1. Enter a string on the keyboard and implement it with Scanner
        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 implement it with Scanner
        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);
    }
}

2.11 cutting strings

Case requirements:

Enter 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. Enter a string on the keyboard and implement it with Scanner

  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. Enter a string on the keyboard and implement it with Scanner
            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 implement it with Scanner
        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 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());
    }
}

2.12 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

public char charAt(int index) returns the char value 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 obtain a new string

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

3 StringBuilder class

3.1 overview of StringBuilder class

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

3.2 differences between StringBuilder class and String class

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

3.3 construction method of StringBuilder class

Common construction methods

Method nameexplain
public StringBuilder()Create a blank variable string object that contains nothing
public StringBuilder(String str)Creates a variable string object based on the contents of the string

Sample code

public class StringBuilderDemo01 {
    public static void main(String[] args) {
        //public StringBuilder(): creates 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());
    }
}

3.4 common member methods of StringBuilder

  • Add and reverse methods

    Method nameexplain
    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): adds data and returns 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);
    }
}

3.5 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 wrong

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

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

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

        //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);
    }
}

3.6 StringBuilder splicing string cases

Case requirements:

Define a method to 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. Defines a method for splicing the data in the int array into a string according to the specified format.
    Return value type String, parameter list int[] arr
  3. In the method, use StringBuilder to splice as required, and convert the result into String to return
  4. Call the method to 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:Defines a method for splicing the data in the int array into a string according to the specified format.
          Return value type String, parameter list int[] arr
        3:In the method, use StringBuilder to splice as required, and convert the result into String to return
        4:Call the method to 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 to receive the result with a variable
        String s = arrayToString(arr);

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

    }

    //Defines a method for splicing the data in the int array into a string according to the specified format
    /*
        Two clear:
            Return value type: String
            Parameter: int[] arr
     */
    public static String arrayToString(int[] arr) {
        //In the method, use StringBuilder to splice as required, and convert 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;
    }
}

Keywords: Java Back-end string

Added by steve@MRS on Wed, 08 Dec 2021 22:47:09 +0200