1, String
(1) Representation of string
java.lang.String represents an immutable character sequence. String is used to represent a sequence composed of characters. It is the most commonly used reference data type. Another string is an array of character (Char) types.
(2) String creation
• standards:
Declare before use
• creation method
(1) Direct assignment: String str = "this" is a string";
(2) Create entity: String s = new String("this is a string");
(3) Create with character array: String(char a [])
char a[] = {'a','b','c'};
String s = new String(char a[])
(4) Create a String with a byte array: String (byte[]bytes,int offset,int length)
public class StringTest { public static void main(String[] args) { // TODO Auto-generated method stub //1. Direct output String s = "this is a string"; String s1 = "this is a string"; //2. By creating entities String s2 = new String("this is a string"); String s3 = new String("this is a string"); //3.char [] byte type char a[] = {'a','b','c'}; String s4 = new String(a); //4.char [] character array takes one segment for output String s5 =new String(a,0,3); //Output (two comparison modes) System.out.println(s.equals(s1));//true System.out.println(s==s1);//true System.out.println(s2==s3);//false System.out.println(s2.equals(s3));//true System.out.println(s4==s5);//false System.out.println(s4.equals(s5));//true /*summary: * == It is used to judge whether two entities are the same. After new creates an entity, because the entities are different, they are different * equals It is used to judge whether the contents of two strings are the same, and only depends on the contents * end */ } }
(3) String common methods
• public char charat (int index) returns the index character in the string
• public int length() returns the length of the string
• public int indexOf(String str) returns the first position of str in the string
• public Boolean equals (string another) compares whether a string is exactly the same as another
• public Boolean equalsignorecase (string other) compares whether a string is the same as another (case is ignored)
• public string replace (char oldChar, char newChar) replaces the oldChar character with the newChar character in the string
• public boolean startsWith(String prefix) determines whether a string starts with a prefix string
• public boolean endsWith(String suffix) determines whether the string starts with the suffix string
• public String toUpperCase() a string is the uppercase form of the string
• public String toLowerCase() a string is the lowercase form of the string
• public String substring(int beginIndex) returns the substring of the string from beginIndex to the end
• public String substring(int beginIndex,int endIndex) returns the substring of the string from beginIndex to endIndex
• public String trim() removes spaces at the beginning and end of the string
• public string [] split (String regex) string is separated by the specified separator and returns the split string array
import java.util.*; public class StringTest { public static void main(String[] args) { // TODO Auto-generated method stub String s = "hello World!"; String s1 = "Hello World!"; System.out.println(s.charAt(2));//Output specified characters System.out.println(s.length());//Length of output string System.out.println(s.indexOf('l'));//Output the position where the first character appears System.out.println(s.equals(s1));//Check whether the two strings are the same System.out.println(s.equalsIgnoreCase(s1));//Case insensitive System.out.println(s.replace('e','a'));//Replace all the same values in the string System.out.println(s.startsWith("hello"));//Determine whether it starts with a string //Note that it is a string. If it is a character, an error will be reported System.out.println(s.endsWith("World"));//Determine whether it ends with a string //It must also be a string and double quotation marks, otherwise an error will occur System.out.println(s.toUpperCase());//Convert all to uppercase System.out.println(s.toLowerCase());//Convert all to lowercase System.out.println(s.substring(2));//Returns a string from the position of the input number to the end System.out.println(s.substring(2, 4));//Returns a string between two numbers System.out.println(s.trim());//Remove the blank form String s2 = "jason,2,1976"; String splitStr[] = s2.split(",");//Character segmentation for(int i = 0;i<splitStr.length;i++) { System.out.println(splitStr[i]); } double d = 1234567.89; String sNumber = String.valueOf(d); System.out.println(sNumber.indexOf("."));//The first position where the character appears } }
(4) Character analyzer StringTokenizer (not recommended, just understand what others write as understanding)
• construction method: StringTokenizer(String str, String delim)
Decomposes the specified string str into delimiters according to the character delim.
• common methods:
• hasMoreTokens(): checks whether there are language symbols in the string. If there are language symbols, it returns true; otherwise, it returns false.
• nextToken(): get the language symbols in the string one by one.
• countTokens(): counts the number of times the nextToken() method is called, which is used to count the number of language symbols in the string.
(equivalent to the lengh () method)
(5) Pattern and Matcher classes (emphasis)
• import java.util.regex
• pattern objects and matcher objects
Pattern pattern1 = Pattern.compile(String regex);
Matcher matcher1 = pattern1.matcher(CharSequence input);
matches(): string matching, return true or false
• find and replace (Matcher class)
replaceAll(String replacement): replaces the given string.
appendReplacement(StringBuffer sb, String replacement): replaces a given character through the string buffer sb
String.
import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringTest { public static void main(String[] args) { // TODO Auto-generated method stub Pattern pattern1, pattern2,pattern3,pattern4;//Pattern class Matcher matcher1,matcher2,matcher3,matcher4;//Matcher class //1. Match to determine whether it matches the desired string pattern1 = Pattern.compile("^java.*");//Inside is a regular expression (target: source string) matcher1 = pattern1.matcher("java Is a programming language");//Matching rules boolean b = matcher1.matches(); System.out.println(b); //2. Split: when splitting strings with multiple conditions pattern2 = Pattern.compile("[, |]"); String[] strs = pattern2.split("java Hello World java,hello,,world||Sun"); System.out.println("Split string"); for(int i = 0;i<strs.length;i++) { System.out.println(strs[i]); } //3. Replacement: text replacement (all) pattern3 = Pattern.compile("regular"); matcher3 = pattern3.matcher("regular Hello World,regular Hello World"); //Replace the first regular data System.out.println("Text replace (all):"+matcher3.replaceAll("java")); //Text replacement (replacement character) pattern4 = Pattern.compile("expression"); matcher4 = pattern4.matcher("expression Hello World,expression Hello World"); StringBuffer sbr = new StringBuffer(); while(matcher4.find())//Find pattern in matcher { matcher4.appendReplacement(sbr, "java"); } matcher4.appendTail(sbr);//When using string buffer, remember to add the tail System.out.println("Text replacement (replacement character):"+sbr.toString()); } }
(6) Regular expression
Metacharacter: a special code specified in a regular expression, which represents the beginning or end of a word, that is, the boundary of a word. It itself does not represent word separators in English, such as spaces, punctuation, line breaks, etc., but is only used to match a position. Escape character: \, if you want to find the metacharacter itself, such as "." or "*". Examples: \. Or\*
Repeat qualifier
2, StringBuffer class
(1) Introduction
• java.lang.StringBuffer represents a variable character sequence
• common construction methods of StringBuffer class
StringBuffer() creates an "empty" StringBuffer object that does not contain a character sequence
StringBuffer(String str) creates a StringBUffer object that contains the same character sequence as the String object str.
(2) Specific operation:
• add character sequence and return
• public StringBuffer append(String str)
• public StringBuffer append(char[ ] str,int offset, int len)
• insert a character sequence at the specified position and return
• public StringBuffer insert(int offset, String str)
• public StringBuffer insert(int offset, double d)
• delete a character sequence from start to end-1 and return
• public StringBuffer delete(int start, int end)
• reverse the character sequence (reset)
• public StringBuffer reverse()
import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringTest { public static void main(String[] args) { // TODO Auto-generated method stub String s ="Mirc"; char c[] = {'a','b','c'}; StringBuffer sb1 = new StringBuffer(s); System.out.println(sb1); //Add strings one by one sb1.append("/").append("sun").append("/").append("oracle"); StringBuffer sb2 = new StringBuffer("number"); //Add char type for(int i = 0;i<c.length;i++) { sb2.append(i); } System.out.println(sb2); //Add at a specific location sb2.insert(0, c); System.out.println(sb2); //Reset string sb2.reverse(); System.out.println(sb2); //Deletes a string at a specific location sb2.delete(4, 6); System.out.println(sb2); } }
(3) Other matters: StringBuffer vs StringBuffer
• StringBuffer is completely equivalent to the methods and functions in StringBuilder.
• StringBuffer is decorated with the synchronized keyword, which has high security. However, it needs to judge the lock every time, which is relatively inefficient.
• in single threaded programs, StringBuilder is more efficient because it does not require locking and does not have multithreading safety.