当前位置:网站首页>String class
String class
2022-07-01 16:48:00 【Xiao Wei loves fried hair】
hello, Hello everyone , Today I will bring you String Class
stay C In language , No string class , stay Java There are string classes in , for instance ,String ret="hello"; This is a variable of string type ,
Let's talk about it String Class has three forms when it is created
public class Test {
public static void main(String[] args) {
String string="hello";
String ret=new String("wyb520");
char[] ch={'a','b','c'};
String str=new String(ch);
}
}One is to write directly
The other is new An object
The last one is by creating an array , then new An array object


Look at my screenshot , We should note that in fact String When creating a variable, this object has value and hash Two memories , Let's switch to String Take a look at the source code of

You can see from this source code , Yes hash and value,value It's a reference
There must be some classmates right String direct new A new object has questions , In fact, the real reason is String Class inherited object class ,object Class is the parent of all classes by default , So you can directly new Instantiate objects
Now let's use the diagram to better understand String Class


string And ret The creation of two variables is shown in the figure above , The special one is the array , First create an array and then new String Copy an array .
Java There is no such thing as \0 ending .
String Is a reference type , Strings are not stored internally , In fact, the string is saved in the array
String s1 = new String("hello");
String s2 = new String("world");
String s3 = s1;
System.out.println(s1.length());
System.out.println(s1.isEmpty());When calculating the length of a string, you must .length(), This bracket cannot be forgotten
Let's continue to draw pictures to better understand the creation of these objects

String String comparison
String sort .Java A total of 4 In the way
1. use == To judge . == Compare whether to reference the same object
For basic types ,== The comparison is the value in the variable ; For reference types == Compare the address in the reference .
public static void main(String[] args) {
int a = 40;
int b = 20;
int c = 40;
System.out.println(a == b); // false
System.out.println(a == c); // true
} public static void main(String[] args) {
String s1=new String("wyb");
String s2=new String("wyb");
System.out.println(s1==s2);//false
}For this reference type

The addresses of the two variables are different . So the answer is false
2. use equals Methods to compare
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = new String("world");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2));//true
System.out.println(s2 == s3); // false
System.out.println(s2.equals(s3)); // false
}3. Use compare to
System.out.println(s1.compareTo(s2));
//compaer to Source code
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}compare to The return is int Type value , Look at the source code, you can got it , Equal length returns 0, Unequal return the difference between two lengths
4.int compareToIgnoreCase
This function is associated with compare to It's the same thing , Just ignore the case
public static void main(String[] args) {
String s1 = new String("WYB");
String s2 = new String("wyb");
System.out.println(s1.compareToIgnoreCase(s2));//0
}
String Class provides string lookup methods
public static void main(String[] args) {
String s = "aaabbbcccaaabbbccc";
System.out.println(s.charAt(3)); // 'b'
System.out.println(s.indexOf('c')); // 6
System.out.println(s.indexOf('c', 10)); // 15
System.out.println(s.indexOf("bbb")); // 3
System.out.println(s.indexOf("bbb", 10)); // 12
System.out.println(s.lastIndexOf('c')); // 17
System.out.println(s.lastIndexOf('c', 10)); // 8
System.out.println(s.lastIndexOf("bbb")); // 12
System.out.println(s.lastIndexOf("bbb", 10));// 3
}char charAt(int index): return index Characters in position , If index Negative or out of bounds , Throw out IndexOutOfBoundsException abnormal
int indexOf(int ch) return ch First occurrence , No return -1
int indexOf(int ch, intfromIndex): from fromIndex The location starts to look for ch First occurrence , No return -1
int indexOf(String str) return str First occurrence , No return -1
int indexOf(String str, intfromIndex): from fromIndex The location starts to look for str First occurrence , No return -1
int lastIndexOf(int ch) Look backwards , return ch First occurrence , No return -1
int lastIndexOf(int ch, intfromIndex): from fromIndex The location starts to look for , Look backwards ch First occurrence , No return -1
int lastIndexOf(String str) Look backwards , return str First occurrence , No return -1
int lastIndexOf(String str, intfromIndex): from fromIndex The location starts to look for , Look backwards str First occurrence , No return -1
Numeric and string conversion
use valueof
public static void main(String[] args) {
// Put other data types Become a string
String s = String.valueOf(123);
String s2 = String.valueOf(12.5);
System.out.println(s);
System.out.println(s2);
}result

public static void main(String[] args) {
// String to number
int data1 = Integer.parseInt("199785");
double data2 = Double.parseDouble("1997.85");
System.out.println(data1);
System.out.println(data2);
}
public static void main(String[] args) {
int a = Integer.valueOf("64");//6*8^1 + 4*8^0 = 52// Default decimal
System.out.println(a);
int a2 = Integer.parseInt("100");// Default decimal
System.out.println(a2);
}public static void main(String[] args) {
String s1 = "abondon";
String ret = s1.toUpperCase();
System.out.println(ret);
System.out.println("s1-> " + s1);
String s2 = "ABANDON";
ret = s2.toLowerCase();
System.out.println(ret);
}
Pay attention here , When using this case, remember that it has not changed
public static void main(String[] args) {
String s = "happy";
// String to array
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i]);
}
System.out.println();
// Array to string
String s2 = new String(ch);
System.out.println(s2);
}format
public static void main(String[] args) {
String s = String.format("%d-%d-%d", 2003 ,2,14);
System.out.println(s);//2003-2-14
}public static void main(String[] args) {
String s1 = "ababcabcdabcde";
String ret = s1.replaceFirst("ab","qquuuuu");// For qquuuuu Replace the first ab
System.out.println(ret);
System.out.println("s1-> "+s1);// Even if you replace , But it has not changed itself
} String splitting
public static void main(String[] args) {
String s1 = "hello wyb happy everyday";
String[] ret = s1.split(" ",4);// Separate in the form of spaces , Divide into 4 Group
for (String s : ret) {
System.out.println(s);// Print
}
}
public static void main(String[] args) {
String str = "192.168.1.1";
String[] ret = str.split("\\.",4);
for (String s : ret) {
System.out.println(s);
}
}
With \. The forms of are divided into 4 Group printing ,\ You need two \\ To compile the , Then two \\ Need 4 strip \\\\ To compile the
public static void main16(String[] args) {
String str = "197\\168\\1\\1";
String[] ret = str.split("\\\\");
for (String s : ret) {
System.out.println(s);
}
}
public static void main(String[] args) {
String str = "abcdef";
String ret = str.substring(1,4);//[1,4)// String interception // The result is bcd The default range is left closed and right open
System.out.println(ret);
System.out.println("=============");
String s = " we are happy ";
System.out.println(s.trim());// Remove the left and right spaces of the current string
//trim Will remove the white space characters at the beginning and end of the string ( Space , Line break , Box drawings, etc ).
System.out.println(s);
}String substitution
public static void main(String[] args) {
String str="we%are%happy";
String ret=str.replaceAll("%"," ");
System.out.println(ret);
}Replace all with spaces %

Today's sharing is here , See you next time ,886
边栏推荐
- 独家消息:阿里云悄然推出RPA云电脑,已与多家RPA厂商开放合作
- OJ questions related to complexity (leetcode, C language, complexity, vanishing numbers, rotating array)
- Kali install Nessus
- Go 语言怎么优化重复的 if err != nil 样板代码?
- Tutorial on the principle and application of database system (003) -- MySQL installation and configuration: manually configure MySQL (Windows Environment)
- Flux d'entrées / sorties et opérations de fichiers en langage C
- How to solve the problem that the battery icon of notebook computer does not display
- 单例模式的懒汉模式跟恶汉模式的区别
- Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)
- What is the effect of choosing game shield safely in the game industry?
猜你喜欢

【直播预约】数据库OBCP认证全面升级公开课

How to solve the keyboard key failure of notebook computer

Alibaba cloud, Zhuoyi technology beach grabbing dialogue AI

Analysis of PostgreSQL storage structure

Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)

Buuctf gold III

免费抽奖 | 《阿巴豆》探索未来系列盲盒数字版权作品全网首发!

想做软件测试的女孩子看这里

MLPerf Training v2.0 榜单发布,在同等GPU配置下百度飞桨性能世界第一

数据库系统原理与应用教程(004)—— MySQL 安装与配置:重置 MySQL 登录密码(windows 环境)
随机推荐
Rhcsa Road
The supply of chips has turned to excess, and the daily output of Chinese chips has increased to 1billion, which will make it more difficult for foreign chips
Principes et applications du système de base de données (006) - - compilation et installation de MySQL 5.7 (environnement Linux)
【flask入门系列】Cookie与Session
How to restore the system of Sony laptop
China nylon 11 industry research and future forecast report (2022 Edition)
Is the securities account given by the head teacher of goucai school safe? Can I open an account?
Authentication processing in interface testing framework
Comprehensively view the value of enterprise digital transformation
拼接字符串,得到字典序最小的结果
Origin2018 installation and use (sorting)
Borui data integrated intelligent observable platform was selected into the "Yunyuan production catalogue" of China Academy of communications in 2022
How to solve the keyboard key failure of notebook computer
SQL question brushing 1050 Actors and directors who have worked together at least three times
数据库系统原理与应用教程(004)—— MySQL 安装与配置:重置 MySQL 登录密码(windows 环境)
P2592 [zjoi2008] birthday party (DP)
免费抽奖 | 《阿巴豆》探索未来系列盲盒数字版权作品全网首发!
Red team Chapter 10: ColdFusion the difficult process of deserializing WAF to exp to get the target
【直播预约】数据库OBCP认证全面升级公开课
Template Engine Velocity Foundation