当前位置:网站首页>String class
String class
2022-07-06 13:08:00 【犇犇犇犇犇犇犇】
String type
Catalog :
List of articles
1. Common methods
stay java in , String is a reference type ,String There are many methods in class that are convenient for us to use , Its functions are applicable to various scenarios , Now let's introduce these common methods .
1.1 Construction method
You can enter the official help manual to search String class , We can see String Class in java.lang The package is imported by default , And it was final The modified .
There are many ways to construct strings , There are three common construction methods
String s1 = "hello";// Abbreviation
String s1 = new String("hello");
char[] ch = new char[]{ 'a','b','c'}; String s1 = new String(ch);
The first method is used most , The most simple .
Let's analyze the memory distribution of these construction methods
1.2 String lookup (indexOf)
Method | usage |
---|---|
string.charAt(index) | It is used to get a character in the string directly through subscript |
string.indexOf(char ch) | Used to find the first character in the string ch The location of |
string.lastindexOf(char ch) | Find characters from back to front ch First occurrence |
string.indexOf(string ch)lastindexof It's fine too | Used to find strings ch First occurrence |
string.indexOf(char ch ,int fromindex)last It's fine too | The front is the same ,fromindex It means to start looking from this position |
public static void main5(String[] args) {
String s1 = "ababacabcdaseasq";
String s2 ="www.baidu.com";
System.out.println(s2.lastIndexOf('.',4));
System.out.println(s2.lastIndexOf('.'));
System.out.println(s1.lastIndexOf('ab'));
}
public static void main4(String[] args) {
String s1 = "hello";
for (int i = 0; i < s1.length(); i++) {
System.out.println(s1.charAt(i));
}
System.out.println("====================");
System.out.println(s1.indexOf('h'));// Find the first character
System.out.println(s1.indexOf('l',3));
System.out.println("====================");
String s2 = "abaabcabcdabsaea";
System.out.println(s2.indexOf("abcd"));
}
1.3 String comparison (equals,compareTo)
Generally, we use == To express , For basic types == The comparison is whether the content is the same , But for reference types == The comparison is whether the same object is referenced , This cannot meet our requirements to compare content .
For reference types, we use equals Compare ,equals The return value of the boolean,java Case insensitive equalsIgnoreCase Method .
String s1 = "hello";
String s2 = "hello";
String s3 = "HELLO";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equalsIgnoreCase(s3));//true
equals You can only compare whether two strings are the same , To compare the size, we need to use compareTo Method because String Realized CompareTo Interface ,compareTo The return value type of is int, Again java A comparison that ignores case is also provided in compareToIgnoreCase Method .
String s1 = "hello";
String s2 = "hello";
String s3 = "HELLO";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareToIgnoreCase(s3));//0
1.4 transformation
- toggle case
Method | function |
---|---|
toUpperCase() | Change all lowercase strings to uppercase ( Letter ) |
toLowerCase() | Change all uppercase strings to lowercase ( Letter ) |
String s1 = "hello";
String s2 = "HELLO";
System.out.println(s1.toUpperCase());//HELLO
System.out.println(s2.toLowerCase());//hello
System.out.println(s1);//hello
System.out.println(s2);//HELLO
Chinese regardless
- String to array (toCharArray)
String s1 = "hello";
char[] ch = s1.toCharArray();
for (char x : ch) {
System.out.println(x);
}
- Numeric conversion string (valueOf)
Method | function |
---|---|
string.valueOf( Basic types i) | Put the basic type i Convert to string type |
Basic types .valueOf(String s) | take string Convert type to base type |
Basic types .parse***(String s)( This conversion is generally used ) | take string Convert type to base type |
Basic types .valueOf(String s radix x) radix Express x Base number (parse*** Also have ) | take String The value of type is pressed x Conversion from decimal to decimal |
String s1 = String.valueOf(123);
String s2 = String.valueOf(12.5);
System.out.println(s1);
System.out.println(s2);
String s3 = String.valueOf(new Student(12));// It can also be an object
System.out.println(s3);
int a = Integer.valueOf("0101",2);//5
System.out.println(a);
int b = Integer.parseInt("1000");//1000
System.out.println(b);
1.5 String replacement (replace)
Method | function |
---|---|
String replaceAll(String regex, String replacement) | Replace all specified contents |
String replaceFirst(String regex, String replacement) | Replace the first content |
String s1 = "ababcabcdeaaweqggh";
System.out.println(s1);
System.out.println(s1.replace('a', 'k'));//kbkbckbcdekkweqggh
System.out.println(s1.replace("ab", "wt"));//wtwtcwtcdeaaweqggh
System.out.println(s1.replaceAll("ab","zc"));//zczcczccdeaaweqggh
System.out.println(s1.replaceFirst("ab","1122"));//1122abcabcdeaaweqggh
1.6 String splitting (split)
Divide the string into several strings according to the specified separator
Method | function |
---|---|
String[] split(String regex) | Split all strings |
String[] split(String regex, int limit) | The string in the specified format , Split into limit Group |
String s1 = "ni hao ma zui jin";
String[] s2 = s1.split(" ",3);
for (String x : s2) {
System.out.println(x);
//ni
//hao
//ma zui jin
}
Escape the specified special separator, such as :,.
String s1 = "255\\255\\255\\255";
// Special characters need to be escaped
String[] s2 = s1.split("\\\\");// Because the string also needs escape , So there are two escape
for (String x : s2) {
System.out.println(x);
}
String s1 = "255.255.255.255";
// Special characters need to be escaped
String[] s2 = s1.split("\\.");
for (String x : s2) {
System.out.println(x);
}
You can also give multiple delimiters to split multiple times
String s1 = "zaiganma nihao&=nibuhao";
String[] s2 = s1.split(" |&");
for(Stiring x : s2){
System.out.println(x);
}
// Split multiple times
s2 = s1.split(" ");
for (String x : s2) {
String[] s3 = x.split("=");
for (String x1 : s3) {
System.out.println(x1);
}
}
1.7 String interception (substring)
This is nothing to say simple
String s1 = "liuyuhao";
System.out.println(s1.substring(3));
System.out.println(s1.substring(2, 5));//[2,5) Left closed right away
1.8 Other operating
trim() Delete the space on the left and right sides of the string , Tabulation , Line break, etc
String s1 = " liu yu ";
System.out.println(s1);
System.out.println(s1.trim());
intern() Manually enter the pool , The following is about constant pool
char[] ch = {
'a','b','c'};
String s1 = new String(ch);
s1.intern();// Manually enter the pool
String s2 = "abc";
System.out.println(s1 == s2);
String Class method , If the return is basically new String object . because String The content in cannot be modified after it is created ,String Is an unchangeable object , So try to avoid direct modification of the string
String s1 = "hello";
s1 += " word";
System.out.println(s1);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("hello");
stringBuilder.append(" word");
Because its bottom layer actually relies on StringBuilder class , Many temporary variables will be created in the middle , So for string modification, we directly use StringBuilder and StringBuffer.String The reason why the content of cannot be changed is String Fields in the class value By final modification , indicate value Cannot reference other character arrays , But you can modify the contents of the reference array .
1.9String Constant pool
String constant pool, also known as StringTable In fact, it is an efficient query data structure .
inter() Manually enter the pool
2.StringBuilder and StringBuffer
Be careful String,StringBuffer,StringBuilder Differences among the three
- String The content of cannot be modified ,StringBuffer and StringBuilder The content of can be modified
- StringBuffer and StringBuilder Both methods are roughly the same
- StringBuffer Synchronous processing , Multithreading is very safe ,StringBuilder If not, do you handle , Unsafe when multithreading .
Here are some key points String There is no way ,StringBuffer The same way
StringBuilder stringBuilder = new StringBuilder();
String s1 = "hello";
stringBuilder.append(s1);// Convert the string to StringBuilder
stringBuilder.insert(0,"lyh ");// stay 0 The subscript position starts inserting ,lyh
stringBuilder.insert(1,1);// stay 1 Insert at subscript position ,1
stringBuilder.deleteCharAt(1);// Delete 1 Of subscript position 1
stringBuilder.setCharAt(0,'z');// take 0 The character in the subscript position is changed to z
stringBuilder.codePointAt(1);// return 1 Of subscript characters ASCII Code value
stringBuilder.reverse();// String reversal
String str = stringBuilder.toString();//StringBuilder turn String
stringBuilder.append("how are you");//String turn StringBuilder
int num = stringBuilder.capacity();
System.out.println(num);// Get the total size of the underlying saved string space
System.out.println(stringBuilder);
Add :
- String format output
String s1 = String.format("%d-%d-%d",2002,06,24);
System.out.println(s1);
- The length of the string is different from that of the array , String length is a method called , Array calls a field
String s1 = "hello";
System.out.println(s1.length());
int[] array = {
1,2,3,4};
System.out.println(array.length);
- Three algorithms for string matching ,BF,BM,KMP, Here is a brief introduction to ,BF The algorithm is a simple two-level cycle of violent matching ,BM The algorithm uses the idea of a good number pair and a bad number pair to process the substring ,KMP The algorithm cites a next Arrays handle substrings and next Optimization of arrays ,nextval Array , You can learn the specific related content .
Learning results of this section
- I understand String class
- Get the hang of String Various methods in the class
- I understand String Constant pool
- Get to know StringBuilder and StringBuffer Also mastered their various methods
- master String,StringBuffer and StringBuilder The difference between
边栏推荐
- How to reduce the shutdown time of InnoDB database?
- RTKLIB: demo5 b34f.1 vs b33
- [algorithm] sword finger offer2 golang interview question 4: numbers that appear only once
- 雇佣收银员【差分约束】
- 系统设计学习(二)Design a key-value cache to save the results of the most recent web server queries
- Error: sorting and subscript out of bounds
- 记录:Navicat Premium初次无法连接数据库MySQL之解决
- What are the advantages of using SQL in Excel VBA
- [算法] 剑指offer2 golang 面试题7:数组中和为0的3个数字
- Devops' future: six trends in 2022 and beyond
猜你喜欢
String类
阿里云微服务(一)服务注册中心Nacos以及REST Template和Feign Client
【GNSS数据处理】赫尔默特(helmert)方差分量估计解析及代码实现
One article to get UDP and TCP high-frequency interview questions!
[algorithm] sword finger offer2 golang interview question 9: subarray with product less than k
继承和多态(下)
[算法] 剑指offer2 golang 面试题12:左右两边子数组的和相等
平衡二叉树详解 通俗易懂
The port is occupied because the service is not shut down normally
[algorithm] sword finger offer2 golang interview question 8: the shortest subarray with a sum greater than or equal to K
随机推荐
MYSQL索引钟B-TREE ,B+TREE ,HASH索引之间的区别和应用场景
4.30 dynamic memory allocation notes
How to reduce the shutdown time of InnoDB database?
几道高频的JVM面试题
TYUT太原理工大学2022数据库题库选择题总结
基本Dos命令
First acquaintance with C language (Part 1)
3月15号 Go 1.18 正式版发布 了解最新特色以及使用方法
抗差估计在rtklib的pntpos函数(标准单点定位spp)中的c代码实现
错误:排序与角标越界
十分钟彻底掌握缓存击穿、缓存穿透、缓存雪崩
Knowledge system of digital IT practitioners | software development methods -- agile
Redis介绍与使用
最短Hamilton路径 (状压DP)
2022 National Games RE1 baby_ tree
rtklib单点定位spp使用抗差估计遇到的问题及解决
面试必备:聊聊分布式锁的多种实现!
【GNSS数据处理】赫尔默特(helmert)方差分量估计解析及代码实现
Error: symbol not found
[algorithm] sword finger offer2 golang interview question 9: subarray with product less than k