String, StringBuffer, StringBuilder -- common methods and differences of "3S" [cloud map Zhilian]

Posted by DedMousie on Mon, 22 Jun 2020 05:35:21 +0200

Introduction to String class

String yes a reference data type is null by default;
String is of final type and cannot be changed and inherited;
The combination of basic type and String will be converted to String type;

1, String common methods

  • length() method

1. Use the length() method of the String class to get the length of the declared String object.

//Spaces are also treated as characters participating in length calculations
String str = "We are students";
int size = srt.length();//The value of size is 15;

The length() method can also be used to control the for loop on array output


//Spaces are also treated as characters participating in length calculations
int [] a = {1,2,3,4,5};
for(int i = 0; i<a.length; i++)
{
    System.out.print(a[i]);//Output: 12345
}

indexOf() method and lastIndexOf() method

1. indexOf() method

indexOf(String s)
This method is used to return the index position where the parameter character s first appears in the specified string. When the indexOf() method of a string is called, the position of S is searched from the beginning of the current string; if the character string s is not retrieved, the return value of the method is - 1

//The index is from 0 to length()-1.
String str = "We are students";
int size = str.indexOf("a");//The value of size is 3
2. lastIndexOf() method

This method is the same as indexOf() method, but the query direction is different. lastIndexOf() method starts from the last index position.

be careful:
In the lastIndexOf() method, the parameter is an empty string '', except for spaces, the returned result is the same as the result of calling the length() method.

charAt() method

This method returns the characters at the specified index.

String str = "We are students";
char mychar = str.charAt(5);//The value of the mychar variable is the character r.

substring() method

1. First use of substring() method

This method returns the truncation from the specified index to the end of the string.

//substring(int beginIndex)
String str = "We are students";
String substr = str.substring(5);//The substr value is e students

2. The second use of substring() method

This method returns from an index to the end of an index.

//substring(int beginIndex , int endIndex)
String str = "We are students";
String substr = str.substring(5,12);//The substr value is e study

trim() method

This method returns a copy of the string, ignoring leading and trailing spaces.

String str = "     Students      ";
String substr = str.trim();//At this point, the value of substr is Students

replace() method and replaceAll() method

1,replace()

This method replaces the specified character or string with a new one.

//replace(char newChar , char oldChar);
String str = "java project";
String substr = str.replace("j" , "J");//At this point, the value of substr is Java proJect
//oldChar appears repeatedly in the string. This method will replace all oldchars with newChar

be careful:
The case of the character oldChar to be replaced should be the same as that of the metacharacter, otherwise it will not be replaced successfully.

String str = "java project";
String substr = str.replace("P" , "t");//The replacement fails

2. The usage of replaceAll() and the difference between replaceAll() and replace()

1, Different parameters
The number of parameters of replace is char and CharSequence, which can support the replacement of character du and string.
The parameter of replaceAll is regex, that is, the replacement based on rule expression. For example, you can change all numeric characters of a string to asterisk through replaceAll("d", "*").

2, Different replacement results
Replace only replaces the first character that appears (affected by javascript), replaceAll replaces all characters, in short, replace replaces the old string sequence with the new string sequence, and replaceAll replaces the string at the position that matches the previous regular expression with the new string.

3, Different usage
replaceAll supports regular expressions, not replace.

String s = "e       ccccc        l";
System.out.println(s.replaceAll(" |c", ""));//The output is el
System.out.println(s.replaceAll(" ", ""));//The output is ecccccl
System.out.println(s.replace(" ", ""));//The output is ecccccl
System.out.println(s.replace(" |c", ""));//The output is e ccccc L
System.out.println(+s.replaceAll(" +|c", ""));//The output is el
System.out.println(+ s.replace(" +", ""));//The output is e ccccc L

startsWith() method and endsWith() method

1,startsWith()

This method is used to determine whether the prefix of the current string object is the string specified by the parameter.

2,endsWith()

This method is used to determine whether the suffix of the current string object is the string specified by the parameter.

String num1 = "22045612";
String num2 = "21304578";
boolean b = num1.startsWith("22");//The value of b is true
boolean b1 = num2.endsWith("78");//The value of b1 is true
boolean b2 = num1.startsWith("30");//The value of b2 is false
boolean b3 = num2.endsWith("45");//The value of b3 is false

equals() method

1,equals()

If two strings have the same character and length, this method returns true for comparison

2,equalslgnoreCase()

This method is used the same way as the equlas() method, but the equlas() method is case sensitive, while equalslgnoreCase() ignores case.

String s1 = "abc;
String s2 = "abc";
String s3 = "ABC"
boolean b = s1.equlas(s2);//The value of b is true
boolean b1 = s1.equalslgnoreCase(s3)//The value of b1 is true
boolean b2 = s1.equlas(s1);//The value of b2 is false
boolean b3 = s1.equalslgnoreCase(s2)//The value of b1 is true

be careful:
When comparing the characters or numbers except the String class, the equals() method cannot be used. If not, the equals() method will compare their addresses.

compareTo() method

The return value of compareTo() is an integer type. It compares the size of the corresponding characters (in ASCII order) first. If the first character and the first character of the parameter are not equal, the comparison ends and returns the difference between them. If the first character and the first character of the parameter are equal, the comparison is made with the second character of the second character and the second character of the parameter, and so on, The length of a character is compared until one of the characters being compared or compared is completely compared

String s1 = "abc";
String s2 = "abcd";
String s3 = "abcdfg";
String s4 = "1bcdfg";
String s5 = "cdfg";
System.out.println( s1.compareTo(s2) ); // -1 (the front is equal, s1 length is less than 1)
System.out.println( s1.compareTo(s3) ); // -3 (the front is equal, s1 length is less than 3)
System.out.println( s1.compareTo(s4) ); // 48 (ASCII code of "a" is 97, ASCII code of "1" is 49, so 48 is returned)
System.out.println( s1.compareTo(s5) ); // -2 (ASCII code of "a" is 97, and ASCII code of "C" is 99, so - 2 is returned)

be careful
The compareTo() method returns 0. 0 only if the equals(Object) method returns true

toLowerCase() method and toUpperCase() method

1,toLowerCase()

Converts a String to lowercase. If the character to be converted is not used, the original String will be returned; otherwise, a new String will be returned, and each character in the original String that has been converted to lowercase will be converted to an equivalent lowercase character. The character length does not change.

2,toUpperCase()

Converts String to uppercase. If the character to be converted is not used, the original String will be returned; otherwise, a new String will be returned, and each character in the original String that has been converted to uppercase will be converted to an equivalent uppercase character. The character length does not change.

String str = "abc ABC";
String newstr1 = str.toLowerCase();//The value of newstr1 is abc abc
String newstr2 = str.toUpperCase();//The value of newstr2 is ABC ABC

split() method

1. First usage

This method can split the string according to the given separator

2. Second usage

This method can split the string according to the given separator and limit the number of times of splitting

String str ="192.18.0.1";
// Divide by "."
String[] firstArray = str.split("\\.");//The value of the firstArray character array is: {192168,0, 1}
// Split twice according to "."
String[] secondArray = str.split("\\.", 2);//The value of the secondArray character array is: {192168.0.1}

contains() method

Returns true if it contains equal characters or strings, and false if it does not.

 public static void main(String[] args) { 
                 String str1 = "hello,world!", str2 = "what?";
                 CharSequence a = "llo"; 
                boolean b = str1.contains(a); 
                System.out.println("The first result is : " + b);  //Return result is true
                  b= str2.contains("!");                                  
                System.out.println("The second result is: " + b); //The return result is false
             }

StringBuffer class

Different from the String class, the StringBuffer class object can be modified many times, and does not generate new unused objects, which also ensures thread safety.

//StringBuffer can only create new objects with the new method
StringBuffer sbf = new StringBuffer();//No initial value
StringBuffer sbf = new StringBuffer(""abc);//Initial value is "abc"
StringBuffer sbf = new StringBuffer(32);//Initial capacity is 32 characters

2, Common methods of StringBuffer

  • append() method

This method is used to append the contents of character generator. With multiple overloaded forms of this method, you can accept any type of data, such as int, boolean, char, String, double or another String generator.

//insert(int offset,age)
StringBuffer sbf = new StringBuffer("hello");
sbf.append("world");//The content of sbf is: hello world

insert() method

This method is used to insert data into the specified location in the string generator. By means of several overloaded forms of this method, basic data types such as int, boolean, char, float, double and other objects can be inserted into string generator.

//insert(int offset,age)
StringBuffer sbf = new StringBuffer("hello");
sbf.insert(5,"world");//The content of sbf is: hello world

delete() method

Remove characters from the substring of this sequence. The substring starts at the specified start and ends at the end-1 of the index. If no such character exists, it ends at the end of the sequence. If start and end are equal, no change occurs.

//delete(int start,int end)
StringBuffer sbf = new StringBuffer("StringBuffer");
sbf.selete(5,10);//At this time, the content of sbf is: stranr

reverse() method

This method can output the strings in reverse order.

StringBuffer sbf = new StringBuffer("StringBuffer");
sbf.reverse();//At this time, the content of sbf is: reffuBgnirtS

StringBuilder class

difference



Topics: Java ascii less Asterisk