2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
I think you have come into contact with strings when learning C language, but in C language, strings can only be represented by
Character array char[10] str = "hello"; or character pointer char *str = "hello";No dedicated String class is provided. In object-oriented Java, the String class and its operations are specifically provided, which makes it more convenient for us programmers to use.
The content of the string cannot be changed.
In String, all operations that may modify the string content create a new object and change the new object.
For example, in the substring:
Some people say: Strings are immutable because the array that holds the characters inside them is finalized and therefore cannot be changed.
public static void main(String[] args) {
final char[] arr = {'h','e','l','l','o'};
arr[0] = 'H';
System.out.println(String.valueOf(arr));//Hello
// arr = new char[]{'h','o'};Error
}
String is a reference data type and does not store the string itself.
public class Test {
public static void main(String[] args) {
//1.直接赋值
String s1 = "first";
//2.new 对象
String s2 = new String("second");
//3. 创建字符数组
char[] arr = {'t','h','i','r','d'};
String s3 = new String(arr);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Notice:
String s1 = “first”;
The Java Virtual Machine (JVM) will first check whether the string "first" already exists in the string constant pool. If it does, it will directly return the reference of the string in the constant pool; if it does not exist, it will add the string to the constant pool and return its reference in the constant pool.
//s1 s2 分别是new 一个新的字符串"hello"
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = "Hello";
String s4 = s1;
System.out.println(s1 == s2);//false
System.out.println(s1 == s4);//true
System.out.println(s1 == s3);//false
//因为Object类中的equals()方法是==实现的,完成不了String类的需求,
//所以String对equals()实现了重写
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = "Hello";
String s4 = s1;
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s4));//true
System.out.println(s1.equals(s3));//false
3. compareTo() compares in lexicographical order, and the return value is int
/*
* 比较的方式有一下两种:
* 1.先一个一个字符相比较,如果出现不同的字符,则返回差值
* 2.如果前x个字符相等,则返回两个字符串的长度差值
* */
String s1 = new String("abc");
String s2 = new String("abcdef");
String s3 = new String("abd");
String s4 = new String("abc");
System.out.println(s1.compareTo(s2));//-3 (3-6)
System.out.println(s1.compareTo(s3));//-1
System.out.println(s1.compareTo(s4));//0
String s1 = new String("Abc");
String s2 = new String("aBcdef");
String s3 = new String("aBd");
String s4 = new String("ABc");
System.out.println(s1.compareToIgnoreCase(s2));//-3 (3-6)
System.out.println(s1.compareToIgnoreCase(s3));//-1
System.out.println(s1.compareToIgnoreCase(s4));//0
method | Function |
---|---|
char charAt(int index) | Returns the character at index. If index is negative or out of bounds, throws IndexOutOfBoundsException. |
int indexOf(int ch) | Returns the position of the first occurrence of ch, or -1 if not found |
int indexOf(int ch, intfromIndex) | Find the first occurrence of ch starting from fromIndex, and return -1 if yes. |
int indexOf(String str) | Returns the position of the first occurrence of str, or -1 if not found |
int indexOf(String str, intfromIndex) | Find the first occurrence of str starting from fromIndex. If not found, return -1. |
int lastIndexOf(int ch) | Search from back to front, return the first occurrence of ch, if not return -1 |
int lastIndexOf(int ch, intfromIndex) | Start from fromIndex and search for the first occurrence of ch from the back to the front. If not found, return -1. |
int lastIndexOf(String str) | Search from back to front, return the first occurrence of str, if not return -1 |
int lastIndexOf(String str, intfromIndex) | Start from fromIndex and search for the first occurrence of str from back to front. If not found, return -1. |
public static void main(String[] args) {
String s = "Hello, how are you today?";
System.out.println(s.charAt(2)); //l
System.out.println(s.indexOf('H')); //0
System.out.println(s.indexOf('l',2)); //从第二个开始找 2
System.out.println(s.indexOf("are")); //11
System.out.println(s.indexOf("are",12)); // 未找到-1
System.out.println(s.lastIndexOf('l')); //从后往前数 3
System.out.println(s.lastIndexOf('l',3));// 从第三个往后数 3
System.out.println(s.lastIndexOf("how"));// 7
System.out.println(s.lastIndexOf("how",6));// 未找到 -1
}
1. Conversion between numbers and strings
String s1 = String.valueOf(1234);
String s2 = String.valueOf(12.34);
String s3 = String.valueOf(true);
String s4 = String.valueOf(new Student("Hanmeimei", 18));
System.out.println(s1);//1234 String
System.out.println(s2);//12.34 String
System.out.println(s3);//true String
System.out.println(s4);//Student@1b6d3586
System.out.println("=================================");
int data1 = Integer.parseInt("1234");
double data2 = Double.parseDouble("12.34");
System.out.println(data1);//1234
System.out.println(data2);//12.34
2. Case conversion
String s1 = "hello";
String s2 = "HELLO";
System.out.println(s1.toUpperCase());//HELLO
System.out.println(s1.toLowerCase());//hello
3. Convert string to character array and character array to string
//字符串转字符数组
String s = "What can I say!";
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
System.out.println();
//字符数组转字符串
String s1 = new String(arr);
System.out.println(s1);
4. Formatting
//格式化
String s = String.format("%d/%02d/%d",2024,07,10);
System.out.println(s);//2024/07/10
method | Function |
---|---|
String replaceAll(String regex, String replacement) | Replace all specified contents |
String replaceFirst(String regex, String replacement) | Replace the first content |
String s = "What can I say say!";
System.out.println(s.replaceAll("say","look"));
System.out.println(s.replaceFirst("say","SAY"));
//What can I look look!
//What can I SAY say!
method | Function |
---|---|
String[] split(String regex) | Split all strings |
String[] split(String regex, int limit) | Split the string into limit groups in the specified format |
//字符串拆分
String s = "字 符 串 拆 分";
String[] str = s.split(" ");
for(String i : str) {
System.out.print(i+"|");
}
System.out.println();
String[] str2 = s.split(" ",2);
for(String i : str2) {
System.out.println(i);
}
/*
* 输出:
字|符|串|拆|分|
字
符 串 拆 分
* */
/*
*拆分是特别常用的操作:
* 一定要重点掌握
*另外有些特殊字符(通配符)作为分割符可能无法正确切分, 需要加上转义.
* */
String s2 = "192.168.1.16" ;
String[] result = s2.split("\.") ;
for(String i: result) {
System.out.println(i);
}
System.out.println("\");
//为了匹配字面上的点号,你需要使用反斜杠()来转义它,
// 但在Java字符串中,反斜杠本身也是一个转义字符,
// 所以你需要使用双反斜杠(\)来表示一个字面量上的反斜杠。
//字符串截取
String s = "What can I say!";
System.out.println(s.substring(6));//an I say!
System.out.println(s.substring(0,3));//What
String s = " yy ds ";
System.out.println(s.trim());//yy ds
The String class cannot be modified, and all modifications will create new objects, which is inefficient.
It only takes 341ms for 10,000 calls. If you want to modify it, it is recommended to use StringBuffer or StringBuilder.
Because String is immutable, Java provides StringBuilder and StringBuffer classes to facilitate string modification. Most of the methods of these two classes are the same.
If you are interested, you can clickOnline documentation
After 1ms using StringBuffer.
Note: String and StringBuilder classes cannot be converted directly. If you want to convert between them, you can use the following principles:
The so-called thread safety is like multiple people going to the toilet. At this time, there is only one toilet. You go in first, close the door, and come out after you are done. During this period, you have exclusive use of this toilet and no one else can come in. Complete the current task first, monopolize the resources, and release the occupied resources after you are done.