Java zero Foundation Series tutorial 08Java string

Supporting video tutorials

This article is a video tutorial for station B

The String class is located in Java Lang package has rich methods

Initialization method of string

/*
 * String: a string of data composed of multiple characters. It can also be regarded as a character array.
 * By looking at the API, we can know
 *         A:The string literal "abc" can also be regarded as a string object.
 *         B:The string is a constant and cannot be changed once it is assigned.
 * 
 * Initialization method:
 *         public String():
 *        public String(String original):Convert string constant value to string
 *
 * String method:
 *         public int length(): Returns the length of this string.
 */
public class StringDemo {
    public static void main(String[] args) {
        // public String():
        String s1 = new String();
        System.out.println("s1:" + s1);
        System.out.println("s1.length():" + s1.length());
        System.out.println("--------------------------");
        //s1:
        //s1.length():0

      //public String(String original): convert the string constant value into a string
        String s6 = new String("abcde");
        System.out.println("s6:" + s6);
        System.out.println("s6.length():" + s6.length());
        System.out.println("--------------------------");
        
        //The string literal "abc" can also be regarded as a string object.
        String s7 = "abcde";
        System.out.println("s7:"+s7);
        System.out.println("s7.length():"+s7.length());
    }
}

Characteristics of string: once assigned, it cannot be changed.
But references can change

public class StringDemo {
    public static void main(String[] args) {
        String s = "hello";
        s += "world";
        System.out.println("s:" + s); // helloworld
    }
}

String s = new String("hello") and string s = "hello"; What's the difference?
The difference between a String literal object and an object created by a constructor

/*
 * String s = new String("hello")And String s = "hello"; What's the difference?
 * have The former creates 2 objects and the latter creates 1 object.
 * 
 * ==:Comparing reference types compares whether the address values are the same
 * equals:By default, the comparison reference type also compares whether the address values are the same, while the String class overrides the equals() method to compare whether the contents are the same.
 */
public class StringDemo2 {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = "hello";

        System.out.println(s1 == s2);// false
        System.out.println(s1.equals(s2));// true
    }
}

 String s5 = "hello";
        String s6 = "hello";
        System.out.println(s5 == s6);// String literal, directly from memory, so true
        System.out.println(s5.equals(s6));// true

Judgment function of String class:

/*
 * String Class judgment function:
 * boolean equals(Object obj):Compare whether the contents of the string are the same, case sensitive
 * boolean equalsIgnoreCase(String str):Compare whether the contents of the string are the same, ignoring case
 * boolean contains(String str):Judge whether the large string contains the small string
 * boolean startsWith(String str):Determines whether a string begins with a specified string
 * boolean endsWith(String str):Determines whether a string ends with a specified string
 * boolean isEmpty():Judge whether the string is empty.
 * 
 * be careful:
 *         The string content is empty and the string object is empty.
 *         String s = "";//The object exists, so the method can be called
 *         String s = null;//Object does not exist, cannot call method
 */
public class StringDemo {
    public static void main(String[] args) {
        // Create string object
        String s1 = "helloworld";
        String s2 = "helloworld";
        String s3 = "HelloWorld";

        // boolean equals(Object obj): compare whether the contents of strings are the same, case sensitive
        System.out.println("equals:" + s1.equals(s2));
        System.out.println("equals:" + s1.equals(s3));
        System.out.println("-----------------------");

        // boolean equalsIgnoreCase(String str): compare whether the contents of strings are the same, ignoring case
        System.out.println("equals:" + s1.equalsIgnoreCase(s2));
        System.out.println("equals:" + s1.equalsIgnoreCase(s3));
        System.out.println("-----------------------");

        // boolean contains(String str): judge whether a large string contains a small string
        System.out.println("contains:" + s1.contains("hello"));
        System.out.println("contains:" + s1.contains("hw"));
        System.out.println("-----------------------");

        // boolean startsWith(String str): determines whether a string starts with a specified string
        System.out.println("startsWith:" + s1.startsWith("h"));
        System.out.println("startsWith:" + s1.startsWith("hello"));
        System.out.println("startsWith:" + s1.startsWith("world"));
        System.out.println("-----------------------");

        // Exercise: boolean endsWith(String str): judge whether the string ends with a specified string, and play by yourself

        // boolean isEmpty(): judge whether the string is empty.
        System.out.println("isEmpty:" + s1.isEmpty());

        String s4 = "";
        String s5 = null;
        System.out.println("isEmpty:" + s4.isEmpty());
        // NullPointerException
        // s5 objects do not exist, so methods cannot be called. Null pointer exception
//        System.out.println("isEmpty:" + s5.isEmpty());
        
    }
}

Get function of String class


/*
 * String Class
 * int length():Gets the length of the string.
 * char charAt(int index):Gets the character at the specified index position
 * int indexOf(int ch):Returns the index of the first occurrence of the specified character in this string.
 *         Why is this type int instead of char?
 *         The reason is: 'a' and 97 can actually represent 'a'. If you write char in it, you can't write the number 97
 * int indexOf(String str):Returns the index of the specified string at the first occurrence in this string.
 * int indexOf(int ch,int fromIndex):Returns the index of the first occurrence of the specified character in this string from the specified position.
 * int indexOf(String str,int fromIndex):Returns the index of the specified string where it first appears after the specified position.
 * String substring(int start):Intercepts the string from the specified position, and defaults to the end.
 * String substring(int start,int end):Intercept the string from the specified position to the end of the specified position.
 */
public class StringDemo {
    public static void main(String[] args) {
        // Define a string object
        String s = "helloworld";

        // int length(): get the length of the string.
        System.out.println("s.length:" + s.length());//10
        System.out.println("----------------------");

        // char charAt(int index): gets the character of the specified index position
        System.out.println("charAt:" + s.charAt(7));//
        System.out.println("----------------------");

        // int indexOf(int ch): returns the index of the first occurrence of the specified character in this string.
        System.out.println("indexOf:" + s.indexOf('l'));
        System.out.println("----------------------");

        // int indexOf(String str): returns the index of the first occurrence of the specified string in this string.
        System.out.println("indexOf:" + s.indexOf("owo"));
        System.out.println("----------------------");

        // int indexOf(int ch,int fromIndex): returns the index of the first occurrence of the specified character from the specified position in this string.
        System.out.println("indexOf:" + s.indexOf('l', 4));
        System.out.println("indexOf:" + s.indexOf('k', 4)); // -1
        System.out.println("indexOf:" + s.indexOf('l', 40)); // -1
        System.out.println("----------------------");

        // Practice by yourself: int indexOf(String str,int)
        // fromIndex): returns the index of the specified string where it first appears from the specified position in the string.

        // String substring(int start): intercepts the string from the specified position, and defaults to the end. Contains the index start
        System.out.println("substring:" + s.substring(5));
        System.out.println("substring:" + s.substring(0));
        System.out.println("----------------------");

        // String substring(int start,intend): intercepts a string from the specified position to the end of the specified position.
        //Include the start index but not the end index
        System.out.println("substring:" + s.substring(3, 8));
        System.out.println("substring:" + s.substring(0, s.length()));
    }
}

Analyze the date of birth according to the ID number

String traversal:


/*
 * Requirement: traverse to get every character in the string
 * 
 * analysis:
 *         A:How can I get every character?
 *             char charAt(int index)
 *         B:How do I know how many characters there are?
 *             int length()
 */
public class StringTest {
    public static void main(String[] args) {
        // Define string
        String s = "helloworld";
        for (int x = 0; x < s.length(); x++) {
            System.out.println(s.charAt(x));
        }
    }
}

Count the number of uppercase letters, lowercase letters and numbers in the string


/*
 * Requirement: count the occurrence times of uppercase, lowercase and numeric characters in a string. (other characters are not considered)
 * give an example:
 *         "Hello123World"
 * result:
 *         Uppercase characters: 2
 *         Lowercase characters: 8
 *         Numeric characters: 3
 * 
 * analysis:
 *         Premise: the string must exist
 *         A:Define three statistical variables
 *             bigCount=0
 *             smallCount=0
 *             numberCount=0
 *         B:Traverse the string to get each character.
 *             length()Combined with charAt()
 *         C:Judge which type the character belongs to
 *             Big: bigCount++
 *             Small: smallCount++
 *             Number: numberCount++
 * 
 *             The difficulty of this problem is how to judge whether a character is large, small or numeric.
 *             ASCII Code table:
 *                 0    48
 *                 A    65
 *                 a    97
 *             Although it is possible for us to make such a comparison according to the figures, we think too much, and there are simpler ones than this
 *                 char ch = s.charAt(x);
 * 
 *                 if(ch>='0' && ch<='9') numberCount++
 *                 if(ch>='a' && ch<='z') smallCount++
 *                 if(ch>='A' && ch<='Z') bigCount++
 *        D:Output results.
 *
 * Exercise: improve the way of giving a string to the way of entering a string with the keyboard.
 */
public class StringTest2 {
    public static void main(String[] args) {
        //Define a string
        String s = "Hello123World";
        
        //Define three statistical variables
        int bigCount = 0;
        int smallCount = 0;
        int numberCount = 0;
        
        //Traverse the string to get each character.
        for(int x=0; x<s.length(); x++){
            char ch = s.charAt(x);
            
            //Judge which type the character belongs to, and char type will be converted to int type
            if(ch>='a' && ch<='z'){
                smallCount++;
            }else if(ch>='A' && ch<='Z'){
                bigCount++;
            }else if(ch>='0' && ch<='9'){
                numberCount++;
            }
        }
        
        //Output results.
        System.out.println("capital"+bigCount+"individual");
        System.out.println("Lowercase letters"+smallCount+"individual");
        System.out.println("number"+numberCount+"individual");
    }
}

String conversion function:


/*
 * String Conversion function of:
 * byte[] getBytes():Converts a string to a byte array.
 * char[] toCharArray():Converts a string to an array of characters.
 * static String valueOf(char[] chs):Convert a character array into a string.
 * static String valueOf(int i):Converts data of type int into a string.
 *         Note: the valueOf method of String class can convert any type of data into a String.
 * String toLowerCase():Convert the string to lowercase.
 * String toUpperCase():Convert string to uppercase.
 * String concat(String str):Concatenate strings.
 */
public class StringDemo {
    public static void main(String[] args) {
        // Define a string object
        String s = "JavaSE";

        // byte[] getBytes(): converts a string into a byte array.
        byte[] bys = s.getBytes();
        for (int x = 0; x < bys.length; x++) {
            System.out.println(bys[x]);
        }
        System.out.println("----------------");

        // Convert character string to array [].
        char[] chs = s.toCharArray();
        for (int x = 0; x < chs.length; x++) {
            System.out.println(chs[x]);
        }
        System.out.println("----------------");

        // static String valueOf(char[] chs): convert the character array into a string.
        String ss = String.valueOf(chs);
        System.out.println(ss);
        System.out.println("----------------");

        // static String valueOf(int i): convert data of type int into a string.
        int i = 100;
        String sss = String.valueOf(i);
        System.out.println(sss);
        System.out.println("----------------");

        // String toLowerCase(): convert the string to lowercase.
        System.out.println("toLowerCase:" + s.toLowerCase());
        System.out.println("s:" + s);
        // System.out.println("----------------");
        // String toUpperCase(): convert the string to uppercase.
        System.out.println("toUpperCase:" + s.toUpperCase());
        System.out.println("----------------");

        // String concat(String str): concatenate strings.
        String s1 = "hello";
        String s2 = "world";
        String s3 = s1 + s2;
        String s4 = s1.concat(s2);
        System.out.println("s3:"+s3);
        System.out.println("s4:"+s4);
    }
}

Convert the first letter of a string to uppercase and the rest to lowercase. (only English uppercase and lowercase characters are considered)


/*
 * Requirement: convert the first letter of a string to uppercase and the rest to lowercase. (only English uppercase and lowercase characters are considered)
 * give an example:
 *         helloWORLD
 * result:
 *         Helloworld
 * 
 * analysis:
 *         A:Get the first character first
 *         B:Gets characters other than the first character
 *         C:Capitalize A
 *         D:Turn B to lowercase
 *         E:C Splice D
 */
public class StringTest {
    public static void main(String[] args) {
        // Define a string
        String s = "helloWORLD";

        // Get the first character first
        String s1 = s.substring(0, 1);
        // Gets characters other than the first character
        String s2 = s.substring(1);
        // Capitalize A
        String s3 = s1.toUpperCase();
        // Turn B to lowercase
        String s4 = s2.toLowerCase();
        // C splice D
        String s5 = s3.concat(s4);
        System.out.println(s5);

        // Optimized code
        // Chain programming
        String result = s.substring(0, 1).toUpperCase()
                .concat(s.substring(1).toLowerCase());
        System.out.println(result);
    }
}

Other functions of String class:

Replacement function:
Remove two spaces in the string
Compares two strings in dictionary order

//        Remove spaces at both ends of the string

        String name = "     ni hao ";
        System.out.println(name.trim());
        System.out.println(name.trim().length());
        System.out.println(name);
        System.out.println(name.length());
//        Replacement function:
        String str2 ="hello world hello kitty";
        String strNew = str2.replace("hello","hehe");
        System.out.println(strNew);
        String strNewName = name.replace(" ","");
        System.out.println(strNewName);
//        Compares two strings in dictionary order
          String s1 = "Lisi";
          String s2 = "lisi";

          System.out.println(s1.compareTo(s2));
          if(s1.compareToIgnoreCase(s2) > 0)
          {
              System.out.println("da");
          }
          else
          {
              System.out.println("Small");
          }

/*
 * Requirement: splice the data in the array into a string according to the specified format
 * give an example:
 *         int[] arr = {1,2,3};    
 * Output result:
 *        "[1, 2, 3]"
 * analysis:
 *         A:Define a string object, but the content is empty
 *         B:First splice the string into a "["
 *         C:Traverse the int array to get each element
 *         D:First judge whether the element is the last one
 *             Yes: just splice the elements and "]"
 *             No: just splice elements and commas and spaces
 *         E:Output spliced string
 * 
 * Implement the code with functions.
 */
public class StringTest2 {
    public static void main(String[] args) {
        // If the array already exists
        int[] arr = { 1, 2, 3 };

        // Write a function to achieve the result
        String result = arrayToString(arr);
        System.out.println("The end result is:" + result);
    }

    /*
     * Two explicit: return value type: String parameter list: int[] arr
     */
    public static String arrayToString(int[] arr) {
        // Define a string
        String s = "";

        // First splice the string into a "["
        s += "[";

        // Traverse the int array to get each element
        for (int x = 0; x < arr.length; x++) {
            // First judge whether the element is the last one
            if (x == arr.length - 1) {
                // Just splice the elements and "]"
                s += arr[x];
                s += "]";
            } else {
                // Just splice elements and commas and spaces
                s += arr[x];
                s += ", ";
            }
        }

        return s;
    }
}

String inversion


import java.util.Scanner;

/*
 * String inversion
 * Example: enter "abc" on the keyboard        
 * Output result: "cba"
 * 
 * analysis:
 *         A:Enter a string on the keyboard
 *         B:Define a new string
 *         C:Traverse the string backwards to get each character
 *             a:length()Combined with charAt()
 *             b:Convert string to character array
 *         D:Concatenate each character with a new string
 *         E:Output new string
 */
public class StringTest3 {
    public static void main(String[] args) {
        // Enter a string on the keyboard
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string:");
        String line = sc.nextLine();

        String s = myReverse(line);
        System.out.println("The result of realizing the function is:" + s);
    }

    /*
     * Two explicit: return value type: string parameter list: String
     */
    public static String myReverse(String s) {
        // Define a new string
        String result = "";

        // Convert string to character array
        char[] chs = s.toCharArray();

        // Traverse the string backwards to get each character
        for (int x = chs.length - 1; x >= 0; x--) {
            // Concatenate each character with a new string
            result += chs[x];
        }
        return result;
    }
}

String splitting

There is a paragraph of lyrics, each sentence ends with a space "". Please output each sentence of lyrics by line

The String class provides a split() method to split a String into substrings, and the result is returned as a String array

public class Lyric {
        public static void main(String[] args) {
            String words="The grass beside the ancient road outside the pavilion is green, and the evening wind holds the sound of willow flute, and the sunset is beyond the mountain";
            String[    ] printword=new String[100];        
               System.out.println("***Original lyrics format***\n"+words);
            System.out.println("\n***Split lyrics format***");
            printword=words.split(" "); 
            for(int i=0;i<printword.length;i++){
                System.out.println( printword[i] );
            }
        }
}

Count the number of occurrences of large and small strings


/*
 * Count the number of occurrences of large and small strings
 * give an example:
 *         In the string "woaijavawozhenaijavawozheneaijavawozhendehnaijavaxinbuxinwoaijavagun"
 * result:
 *         java Five times
 * 
 * analysis:
 *         Premise: you already know the big string and the small string.
 * 
 *         A:Define a statistical variable with an initialization value of 0
 *         B:First, find the position where the small string appears for the first time in the large string
 *             a:If the index is - 1, it indicates that it does not exist, then the statistical variable is returned
 *             b:The index is not - 1, indicating that there is a statistical variable++
 *         C:Take the length of the index + small string as the starting position, intercept the last large string, return a new string, and re assign the value of the string to the large string
 *         D:Back to B
 */
public class StringTest5 {
    public static void main(String[] args) {
        // Define large string
        String maxString = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
        // Define small string
        String minString = "java";

        // Implementation of write function
        int count = getCount(maxString, minString);
        System.out.println("Java In the large string:" + count + "second");
    }

    /*
     * Two explicit: return value type: int parameter list: two strings
     */
    public static int getCount(String maxString, String minString) {
        // Define a statistical variable with an initialization value of 0
        int count = 0;        
        int index;
        //Check, assign and judge first
        while((index=maxString.indexOf(minString))!=-1){
            count++;
            maxString = maxString.substring(index + minString.length());
        }

        return count;
    }
}

Solution 2

  // Define large string
        String maxString = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
        // Define small string
        String minString = "java";
        String[] array = maxString.split(minString);
         System.out.println("Java In the large string:" + (array.length -1) + "second");

StringBuffer and StringBuilder

When frequently modifying strings (such as string connection), using StringBuffer class can greatly improve the efficiency of program execution

StringBuffer declaration
StringBuffer sb = new StringBuffer();
StringBuffer sb = new StringBuffer("aaa");
Use of StringBuffer
sb.toString(); // Convert to String type
sb.append("aaa"); // Append string

Convert a number string into a comma separated number string, that is, every three numbers are separated by commas from the right

Tags: Java

Posted by cameeob2003 on Fri, 13 May 2022 14:50:17 +0300