Detailed sorting of Java String class operation methods

Keywords: Java Back-end

The basic operations of String class can be divided into the following categories:

1. Basic operation method

2. String comparison

3. Conversion between string and other data types

4. Character and string lookup

5. Interception and splitting of strings

6. String replacement and modification
1, String basic operation method

First, let's talk about the basic operation methods. The basic operation methods of string include the following:

(1) Get string length()

(2) Gets the i-th character charAt(i) in the string

(3) Get the character method getchars at the specified position (4 parameters)

1. Get string length method length()

Format: int length = str.length();

2. Get the ith character in the string method charAt(i)

Format: char ch = str.charat (I)// I is the index number of the string. The characters at any position of the string can be obtained and saved to the character variable

3. Get the character method getchars at the specified position (4 parameters)

Format: char array[] = new char[80]// First, create a char array with a large enough capacity. The array name is array

str.getChars(indexBegin,indexEnd,array,arrayBegin);

Explain the meaning of the four parameters in parentheses:

1. indexBegin: the starting index of the string to be copied

2. indexEnd: end index of the string to be copied, indexEnd-1

3. Array: the array name of the char type array defined earlier

4. arrayBegin: the index number at the beginning of array storage

In this way, we can copy all the characters in the desired range in the string to the character array and print out the character array.

Methods similar to getChars() have a getBytes(), which are basically the same, except that the getBytes() method creates an array of byte type, and the byte encoding is the default character set encoding, which is a character represented by encoding.

Here is a brief demonstration of the usage of the three methods:

//Basic operation methods of String class
public class StringBasicOpeMethod {
    public static void main(String args[]){
        String str = "How can we become as good as chess brother? Forget it, brag!"; //Define a string
        System.out.println(str);  //Output string
        /***1,length()Method***/
        int length = str.length();//Get string length
        System.out.println("The length of the string is:"+length);
        /***2,charAt()Method***/
        char ch = str.charAt(7);  //Get the character with index 7
        System.out.println("The 8th character in the string is:"+ch);
        /***3,getChars()Method***/
        char chardst[] = new char[80]; //Define a character array with a capacity of 80 to store a string of characters extracted from a string
        str.getChars(0,14,chardst,0);
        //System.out.println("the contents stored in the character array are:" + chardst ")// Error, code output
        System.out.println(chardst); //**No other strings are allowed in parentheses
    }
}

2, String comparison

We know that explicit values can be easily compared, so how should strings be compared? String comparison is to compare the two strings character by character from left to right. The comparison is based on the uncoded value of the current character until the size of two different characters is compared.

String comparison can also be divided into two categories: one is the comparison of string size. Such comparison has three results: greater than, equal to and less than; Another kind of comparison method is to compare whether two strings are equal. In this way, there are only two comparison results, true and false.

1,First, let's take a look at the first method of comparing size requirements:

     (1)String size comparison method without ignoring string case compareTo(another str)

               Format: int result = str1.compareTo(str2);

            Output three comparison results: if the string Unicode value<Parameter string Unicode Value, and the result returns a negative integer; If the string Unicode value=Parameter string Unicode Value, the result returns 0; If the string Unicode value>Parameter string Unicode Value, and the result returns a positive integer.

     (2)  String size comparison method when string case is ignored compareTOIgnoreCase(another str)

               Format: int result = str1.compareToIgnoreCase(str2);

            In case of ignoring string case, three comparison results are returned: three comparison results are output: if the string is Unicode value<Parameter string Unicode Value, and the result returns a negative integer; If the string Unicode value=Parameter string Unicode Value, the result returns 0; If the string Unicode value>Parameter string Unicode Value, and the result returns a positive integer.

2,Then look at the second method to judge whether the two strings are equal(In case of equality, the length of the two must be equal)Methods in requirements:

        (1)Method for judging string equality without ignoring string case eaquals(another str)

               Format: boolean result = str1.equals(str2);

               if and only if str1 and str2 Is equal in length and corresponds to the position of the character Unicode Codes are exactly the same, return true,Otherwise return false

         (2)   Method for judging string equality when ignoring string case equalsIgnoreCase(another str)

                Format: boolean result = str1.equals(str2);

The demo is as follows:

public class StringCompareMethod {
    public static void main(String args[]){
        String str1 = "elapant";
        String str2 = "ELEPANT";  //Define two strings
        String str3 = "Apple";
        String str4 = "apple";
        /***1,compareTo Method***/
        //String character case is not ignored
        if(str1.compareTo(str2)>0){
            System.out.println(str1+">"+str2);
        }else if(str1.compareTo(str2) == 0){
            System.out.println(str1+"="+str2);
        }else{
            System.out.println(str1+"="+str2);
        }
        /***2,compareToIgnoreCase()Method***/
        //Ignore string character case
        if(str1.compareToIgnoreCase(str2)>0){
            System.out.println(str1+">"+str2);
        }else if(str1.compareToIgnoreCase(str2) == 0){
            System.out.println(str1+"="+str2);
        }else{
            System.out.println(str1+"<"+str2);
        }
        /***3,equals()Method***/
        //String character case is not ignored
        if(str3.equals(str4)){
            System.out.println(str3+"="+str4);
        }else{
            System.out.println(str3+"!="+str4);
        }
        /***4,equalsIgnoreCase()Method***/
        //Ignore string character case
        if(str3.equalsIgnoreCase(str4)){
            System.out.println(str3+"="+str4);
        }else{
            System.out.println(str3+"!="+str4);
        }
    }
}

3, Conversion of strings to other data types

Sometimes we need to make a conversion between the String and other data types, such as changing the String data into integer data, or conversely changing the integer data into String data. "20" is the String, and 20 is the integer number. We all know that forced type conversion and automatic type conversion can be used to convert between integer and floating-point types, so the data type conversion method provided by String class is required for "20" and "20" which belong to different types of data

public class StringConvert {
  public static void main(String args[]){
    /***Converts a string type to another data type***/
    boolean bool = Boolean.getBoolean("false"); //Convert string type to boolean type
    int integer = Integer.parseInt("20"); //Convert string type to integer
    long LongInt = Long.parseLong("1024"); //Convert string type to long integer
    float f = Float.parseFloat("1.521"); //Convert string type to single precision floating point
    double d = Double.parseDouble("1.52123");//Convert string type to double precision floating point
    byte bt = Byte.parseByte("200"); //Convert string type to byte type
    char ch = "Chess brother".charAt(0);
    /***Convert other data types to string type method 1***/
    String strb1 = String.valueOf(bool); //Converts a boolean type to a string type
    String stri1 = String.valueOf(integer); //Converts an integer to a string type
    String strl1 = String.valueOf(LongInt); //Converts a long integer to a string type
    String strf1 = String.valueOf(f); //Converts a single precision floating-point type to a string type
    String strd1 = String.valueOf(d); //Convert double type to string type
    String strbt1 = String.valueOf(bt); //Convert byte to string type
    String strch1 = String.valueOf(ch); //Convert character type to string type
  }
}

4, String lookup

Sometimes we need to find some strings or a character in a long String. The String class just provides corresponding search methods. These methods return the index value of the target search object in the String, so they are integer values. The specific classification is as follows:

String lookup can be divided into two categories: String lookup and single character lookup, and the lookup can be divided into the first occurrence position and the last occurrence position of the lookup object in the string. By expanding one step, we can narrow the search range and find the first or last occurrence position within the specified range.

(1) Find where characters appear

       1,indexOf()method

            Format: 1 str.indexOf(ch);

                      2,str.indexOf(ch,fromIndex); //Contains the fromIndex location

            Format 1 returns the index of the first occurrence of the specified character in the string  

            Format 2 returns the index number of the character that appears for the first time after the specified index position

       2,lastIndexOf()method

            Format: 1 str.lastIndexOf(ch);

                      2,str.lastIndexOf(ch,fromIndex);

            Format 1 returns the index of the last occurrence of the specified character in the string

            Format 2 returns the index number of the last occurrence of the character before the specified index position

(2) Find where the string appears

      1,indexOf()method  

           Format: 1 str.indexOf(str);

                     2,str.indexOf(str,fromIndex);

           Format 1 returns the index of the first occurrence of the specified substring in the string

           Format 2 returns the index number of the substring that first appears before the specified index position

       2,lastIndexOf()method

            Format: 1 str.lastIndexOf(str);

                      2,str.lastIndexOf(str,fromIndex); 

            Format 1 returns the index of the last occurrence of the specified substring in the string

            Format 2 returns the index number of the last occurrence of the substring before the specified index position

Look at the code:

//Character and string lookup
public class StringSearchChar {
  public static void main(String args[]){
    String str = "How qi bocome handsome like qi ge"; //Define a long string
    System.out.println("The string is:"+str);
    /***1,indexOf()Method to find the first occurrence position of a character format 1,2***/
    int index1 = str.indexOf(" "); //Find the index of the first space
    int index2 = str.indexOf(" ",4); //Find the index of the first space after index 4
    System.out.println("The index of the first space is:"+index1);
    System.out.println("The index of the first space after index 4 is:"+index2);
    System.out.println("*****************");
    /***2,lastIndexOf()Method to find the last position of a character. Format 1,2***/
    int index3 = str.lastIndexOf(" "); //Find the index of the last space
    int index4 = str.lastIndexOf(" ",10);//Find the index of the first space after index 10
    System.out.println("The index of the last space is:"+index3);
    System.out.println("The index of the last space before index 10 is:"+index4);
    System.out.println("*****************");
    /***3,indexOf()Method to find the first occurrence of a substring. Format 1,2***/
    int index5 = str.indexOf("qi"); //Find the index where the "qi" substring first appears
    int index6 = str.indexOf("qi",5);//Find the index of the first occurrence position of substring "qi" after index 5
    System.out.println("Substring qi The index number of the first occurrence is:"+index5);
    System.out.println("Substring after index 5 qi The index number of the first occurrence is:"+index6);
    System.out.println("*****************");
    /***4,lastIndexOf()Method to find the last occurrence of a substring. Format 1,2***/
    int index7 = str.lastIndexOf("qi");
    int index8 = str.lastIndexOf("qi",5);
    System.out.println("Substring qi The index number of the last occurrence is:"+index7);
    System.out.println("Substring after index number 5 qi The index number of the last occurrence is:"+index8);
  }
}

5, Interception and splitting

This kind of method is to intercept a substring in a long string or split and save all the strings into a string array according to the requirements of regular expression. The specific method is as follows:

(1) Interception method

  1,substring()method    

        Format 1: String result = str.substring(index);

        Format 2: String result = str.substring(beginIndex,EndIndex);//Actual index number [beginIndex,EndIndex-1]

        Result: truncate the string in the range

(2) Split method

   1,split()method

        Format 1: String strArray[] = str.split(regular expression );// The split result is saved to the string array

        Format 2: String strArray[] = str.split(Regular expressions, limit);

The code example is as follows

//String interception and splitting
public class StringCutAndSplit {
  public static void main(String args[]){
    String str = "How to cut and split strings"; //Define string
    System.out.println("The string is:"+str);
    int length = str.length(); //Get the string length and save it to the variable
    System.out.println("The string length is:"+length);
    /***1,substring()Method to extract the first word and the last word***/
    //First, use indexOf() and lastIndexOf() methods to find the index number of the space before and after the first word and the last word
    //The left range index of the first word is 0, and the right range index of the last word is length-1
    int firstIndex = str.indexOf(' '); //Find the location of the first space
    int lastIndex = str.lastIndexOf(' '); //Find the location of the last space
    System.out.println("The index number of the first space is:"+firstIndex);
    System.out.println("The index number of the last space is:"+lastIndex);
    //The substring() method is used to extract the first and last words according to the index range of the first and last words
    String firstWord = str.substring(0,firstIndex); //Cut out the first word
    String lastWord = str.substring(lastIndex+1,length);//Intercept the last word
    System.out.println("The first word is:"+firstWord);
    System.out.println("The last word is:"+lastWord);
    /***1,split()Method to split all words***/
    String stringArray[] = str.split(" "); //Split all words according to the space requirements and save them in the string array
    System.out.println("The words after splitting are:"); //Output prompt information
    for(int i = 0;i<stringArray.length;i++){
      System.out.print(stringArray[i]+"\t");
    }
  }
}

6, Replace or modify

Finally to the last kind of method, happy!! Sometimes we need to replace or modify some substrings in the original String. At this time, we also need some simple, fast and easy-to-use methods provided by the String class

(1) concat() method: merge strings

     Format: String result = str1.concat(str2);   //Merge str1 and str2

(2) toLowerCase() method: converts all characters to lowercase

     format:  String result = str.toLowerCase();

(3) toUpperCase() method: converts all characters to uppercase

     Format: String result = str.toUpperCase();          

(4)replaceAll(), replaceFirst() methods: regular expressions need to be matched

The code is as follows:

//String replacement and modification
public class StringFindandReplace {
  public static void main(String args[]){
    String str1 = "vbasic";
    String str2 = "Vbasic";
    System.out.println("str1 = "+str1);
    System.out.println("str2 = "+str2);
    /***1,concat()Method to merge two strings***/
    String str3 = str1.concat(str2);
    System.out.println("str1 and str2 The combined string is:"+str3);
    /***2,toLowerCase()Method converts all str1 characters to lowercase***/
    String str4 = str1.toLowerCase();
    System.out.println("str1 Convert all characters to lowercase:"+str4);
    /***3,toUpperCase()Method converts all str2 characters to uppercase***/
    String str5 = str2.toUpperCase();
    System.out.println("str2 Convert all characters to uppercase:"+str5);
    /***4,Realize the replacement of string, and the content of the original string remains unchanged***/
    String str6 = str1.replaceFirst("(?i)VBASIC","C++");
    String str7 = str2.replaceFirst("(?-i)VBASIC","C++");
    System.out.println("Replaced str1: "+str6);
    System.out.println("Replaced str2:"+str7);
  }
}

Posted by Paavero on Tue, 02 Nov 2021 13:53:08 -0700