Know the use of String class and String
1. Create a string:
(1) Common ways to construct String:
① Method 1: (Direct assignment)
String str1 = "hello";
② Method two: (construction method)
String str2 = new String("hello");
③ Method three:
char[] value = {
'a','b','c','d'};
String str3 = new String(value);
The difference between the three methods:
Interview: The difference between the instantiation of the two objects in the String class
1. Direct assignment : Only a pair of memory space will be opened, and the string object can be automatically saved in the object pool for next use.
2. Construction method : two heap memory spaces will be opened up, and will not be automatically saved in the object pool. You can use the intern() method to manually enter the pool
(2) The basic concept of String:
string is a reference type , similar to the C language pointer
references: only to the data structure of objects
(we can imagine a reference label "attached" to an object, an object can be attached to one or more tags ; If an object does not have a label, it will be garbage collected by the JVM)
String str = "cool";
String str2 = "cool";
At this time, someone may ask:
if str is modified, will str2 change accordingly?
String str = "cool";
String str2 = "cool";
str = "beautiful";
System.out.println(str2);
//执行结果: cool
In fact, code like str = "beautiful" does not modify the string, but makes the reference of str point to a new String object. (The string content is immutable)
2. String comparison is equal:
(1) == type: the
basic data type compares the size of the value
int x = 10 ;
int y = 10 ;
System.out.println(x == y);
// 执行结果
true
For String, if it is a direct assignment, because the two references point to the same object in the string constant pool, it returns true
String str1 = "Hello";
String str2 = "Hello";
System.out.println(str1 == str2);
// 执行结果
true
If it is the construction method, the two references each point to two objects, because two objects are new, the result is false
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2);
// 执行结果
false
So, String comparisons using == not compare the contents of the string, but compare two references point to the same object
(2) In Java, if you want to compare the contents of strings, you must use the equals method provided by the String class
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1.equals(str2));
// System.out.println(str2.equals(str1)); // 或者这样写也行
// 执行结果
true
3. Conversion of characters, bytes, and strings
(1) Characters and strings
String can be converted to char[]
Code example:
String str = "hello" ;
System.out.println(str.charAt(0)); // 下标从 0 开始
// 执行结果
h
String and character array conversion
String str = "helloworld" ;
// 将字符串变为字符数组
char[] data = str.toCharArray() ;
for (int i = 0; i < data.length; i++) {
System.out.print(data[i]+" ");
}
// 字符数组转为字符串
System.out.println(new String(data)); // 全部转换
System.out.println(new String(data,5,5)); // 部分转换
(2) Bytes and strings
Convert between String and byte[]
Code example:
String str = "helloworld" ;
// String 转 byte[]
byte[] data = str.getBytes() ;
for (int i = 0; i < data.length; i++) {
System.out.print(data[i]+" ");
}
// byte[] 转 String
System.out.println(new String(data));
So when to use byte[] and when to use char[]?
byte[] : The String is processed in a byte-by-byte manner. This is suitable for use in network transmission and data storage scenarios, and is more suitable for operating on binary data.
char[] : The String is processed in a character-by-character manner, which is more suitable for operation on text data, especially when it contains Chinese.
4. Common operations on strings:
(1) String comparison:
String str1 = "hello" ;
String str2 = "Hello" ;
System.out.println(str1.equals(str2)); // false
System.out.println(str1.equalsIgnoreCase(str2)); // true
System.out.println("a".compareTo("A")); // 32
(2) String search:
Code example:
string search, the best and most convenient one is contains()
String str = "helloworld" ;
System.out.println(str.contains("world")); // true
Use indexOf() method for location lookup
String str = "helloworld" ;
System.out.println(str.indexOf("world")); // 5,w开始的索引
System.out.println(str.indexOf("cool")); // -1,没有查到
if (str.indexOf("hello") != -1) {
System.out.println("可以查到指定字符串!");
}
Determine the beginning or end:
String str = "**@@helloworld!!" ;
System.out.println(str.startsWith("**")); // true
System.out.println(str.startsWith("@@",2)); // ture
System.out.println(str.endwith("!!")); // true
(3) String replacement:
String replacement processing:
String str = "helloworld" ;
System.out.println(str.replaceAll("l", "_"));
System.out.println(str.replaceFirst("l", "_"));
Note:
Since the string is an immutable object, the replacement does not modify the current string, but generates a new string
(4) String splitting:
Realize string split processing:
String str = "hello world " ;
String[] result = str.split(" ") ; // 按照空格拆分
for(String s: result) {
System.out.println(s);
}
Partial split of string:
String str = "hello world " ;
String[] result = str.split(" ",2) ;
for(String s: result) {
System.out.println(s);
}
Split IP address:
String str = "192.168.1.1" ;
String[] result = str.split("\\.") ;
for(String s: result) {
System.out.println(s);
}
note:
- The characters "| "," * "," +" must be added with escape characters, preceded by "\ ".
- And if it is "", then it has to be written as "\ \ ".
- If there are multiple separators in a string, you can use "|" as a hyphen.
Split multiple times:
String str = "name=zhangsan&age=18" ;
String[] result = str.split("&") ;
for (int i = 0; i < result.length; i++) {
String[] temp = result[i].split("=") ;
System.out.println(temp[0]+" = "+temp[1]);
}
(5) Interception of string:
Code example:
String str = "helloworld" ;
System.out.println(str.substring(5));
System.out.println(str.substring(0,5));
note:
- Index starts from 0
- Pay attention to the way of writing the interval before closing and opening, substring(0, 5) means the character containing subscript 0, not subscript 5.
(6) Other operations:
Observe the use of trim() method:
String str = " hello world " ;
System.out.println("["+str+"]");
System.out.println("["+str.trim()+"]");
Observe the isEmpty() method:
System.out.println("hello".isEmpty());
System.out.println("".isEmpty());
System.out.println(new String().isEmpty());
Capitalize the first letter:
public static void main(String[] args) {
System.out.println(fistUpper("yuisama"));
System.out.println(fistUpper(""));
System.out.println(fistUpper("a"));
}
public static String fistUpper(String str) {
if ("".equals(str)||str==null) {
return str ;
}
if (str.length()>1) {
return str.substring(0, 1).toUpperCase()+str.substring(1) ;
}
return str.toUpperCase() ;
}
5. The difference between String, StringBuffer and StringBuilder (interview)
(1) The content of String cannot be modified, while the content of StringBuffer and StringBuilder can be modified. Consider using StingBuffer if the string is frequently modified.
(2) String, StringBuilder suitable for single-threaded
StringBuffer suitable for multithreading , security
(3) String, its underlying splice is optimized for StringBuilder