Java string

Keywords: Java Back-end

  catalogue

1, Traversal string

2, Count the number of various characters

3, Splice string

4, String inversion

1, Traversal string

    public static void StringTest03(){
        System.out.println("Please enter a string:");
        String str = sc.nextLine();
        for (int i = 0; i < str.length(); i++){
            System.out.println(str.charAt(i));
        }
    }

Traversing arrays with a for loop

Use the length() method to obtain the length of the string

Use the charAt(n) method to obtain the characters at the specified index n

2, Count the number of various characters

 public static void StringTest04(){
        System.out.println("Please enter a string");
        String str = sc.nextLine();
        //Define three statistical variables
        int bigCount = 0;
        int smallCount = 0;
        int numCount = 0;
        int emCount = 0;
        //Traverse the string and count the number of occurrences of various characters
        for(int i = 0; i < str.length(); i++){
            if((str.charAt(i) >= 'a') && (str.charAt(i) <= 'z')){
                smallCount++;
            }else if ((str.charAt(i) >= 'A') && (str.charAt(i) <= 'z')){
                bigCount++;
            }else if ((str.charAt(i) >= '0') && (str.charAt(i) <= '9')){
                numCount++;
            }else{
                emCount++;
            }
        }
        System.out.println("Lowercase character: "+smallCount+"Uppercase character: "+bigCount+"number: "+numCount+"Space: "+emCount);
    }

Enter the string from the keyboard, set the statistical variable, and traverse through the loop. Access each character in the string, judge which type the character belongs to, complete data statistics, and finally output statistical results.

3, Splice string

Requirements: define a method to splice the data in the int array into a string according to the specified format.

public class Test {
    public static void main(String[] args) {
        //Define an integer array
        int [] arr = {1, 2, 3};
        String Str = arrayToString(arr);
        System.out.println("The string generated by the integer array is: "+ Str);
    }
    /*
    Method for splicing arrays into strings:
    Parameter: int [] arr
    Return value type: String
     */
    public static String arrayToString(int [] arr){
        String str = new String();
        str += "[";
        for (int i = 0; i < arr.length; i++){
            if(i == arr.length - 1){
                str += arr[i];
            }else{
                str += arr[i] + ", ";
            }
        }
        str += "]";
        return str;
    }
}

Idea: define an integer array, use static initialization to complete the initialization of array elements, set an arrayToString method inside the Test class, the parameter is an integer array, return a string, and complete the splicing of self string by traversing the array in the method. Here, '+' is used to complete the splicing.

Advanced version:

Public class Test{

    public static void main(String [] args){
        
      //Define an integer array
      
        int [] array = [1, 2, 3];
        
        String s = arrayToString(array);  
        System.out.println("The spliced string is: " + s);

    }
    
    public static String arrayToString(int [] arr){

        //Define a BufferBuilder type string

        StringBuilder str = new StringBuilder();

        //Traversing an array through a for loop
    
        for(int i = 0; i < arr.length; i++){

            str.append(arr[i]);

        }

        //Define a String variable as the return value

        String s = str.toString();

        return s;    

    }

}

Idea: use the StringBuffer class to create a variable string object, and complete string splicing through the class's unique method append()

PS: append (any type) adds data and returns the object itself, focusing on understanding the returned object itself

For example:   

StringBuilder str1 = new StringBuilder();

StringBuilder str2 = str1.append("zbc");

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


The output result is true, because adding data through the append() method returns the object itself,
So str1 and str2 actually create an object.
PS: in java, "= =" compares the address of the reference data, because the reference data is
Stack memory stores the address of the data, and the value of the data is stored in heap memory.

4, String inversion

Requirements: input a string from the keyboard and complete the inversion of the string through a method

import java.util.Scanner;
public class Test {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        //Enter a string from the keyboard
        System.out.println("Please enter a string");
        String str1 = sc.nextLine();
        //Complete the inversion of the string through the defined method
        String str2 = reverse(str1);
        System.out.println("The inverted string is: " + str2);
    }
    public static String reverse(String str){
        //Define an empty string
        String str2 = "";
        //Traverses the incoming string through the for loop
        for (int i = str.length(); i > 0; i--){
            str2 += str.charAt(i - 1);
        }
        return str2;
    }
}

Idea: reversing the string also uses the string splicing principle of, but traverses the string in reverse order, and uses the charAt() method to obtain the characters of the specified index.

Advanced version:

public static void reverseUp() {
        //Prompt the user for a string
        System.out.println("Please enter a string: ");
        String s = sc.nextLine();
        //According to the string s, create a variable string of StringBuilder class
        StringBuilder str = new StringBuilder(s);
        //Use the reverse() method to complete the inversion
        str.reverse();
        /*
        System.out.println("Test: "+ str); 
        In fact, you can directly output the inverted string at this time, but in order to
        Achieve the effect of outputting String class String, or create String
        Class, and complete the conversion of data
         */
        //Converts the inverted variable String into a String of the String class
        s = str.toString();
        System.out.println("Inverted string: " + s);
    }

Idea: use the reverse() method of StringBuilder class to complete the inversion

java supports chain calls, so the method to complete string inversion can be written as follows:

public static String reverseUpp(String s){

    return new StringBuilder(s).reverse().toString();

}

PS: it is explained in the advanced version of splicing

StringBuilder to String: use the toString() method

String to StringBuilder: use the construction method of StringBuilder

//StringBuilder to String

StringBuilder str1 = new StringBuilder("abc");

String s = str1.toString();

//String to StringBuilder

String str2 = "zbc";

StringBuilder t = new StringBuilder(str2);

Posted by jgh84 on Fri, 29 Oct 2021 21:07:49 -0700