当前位置:网站首页>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
边栏推荐
- Introduction to software engineering - Chapter 6 - detailed design
- EndeavourOS移动硬盘安装
- 【PyG】文档总结以及项目经验(持续更新
- C語言輸入/輸出流和文件操作
- 如何使用phpIPAM来管理IP地址和子网
- 广东用电量大跌,说明高新技术产业替代高能耗产业已取得初步成果
- Why is the pkg/errors tripartite library more recommended for go language error handling?
- Building blocks for domestic databases, stonedb integrated real-time HTAP database is officially open source!
- 拼接字符串,得到字典序最小的结果
- sql刷题586. 订单最多的客户
猜你喜欢

【PyG】文档总结以及项目经验(持续更新

Introduction to software engineering - Chapter 6 - detailed design
![[jetsonnano] [tutorial] [introductory series] [III] build tensorflow environment](/img/0e/52e37527bc717c7a55741725087bad.png)
[jetsonnano] [tutorial] [introductory series] [III] build tensorflow environment

VMware 虛擬機啟動時出現故障:VMware Workstation 與 Hyper-v 不兼容...

C language input / output stream and file operation

程序员职业生涯真的很短吗?
![[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting](/img/82/3bb382893682a30e8af130365ec4ef.jpg)
[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting

SQL question brushing 586 Customers with the most orders

How to cancel automatic search and install device drivers for laptops

Are you still using charged document management tools? I have a better choice! Completely free
随机推荐
模板引擎Velocity 基礎
嗨 FUN 一夏,与 StarRocks 一起玩转 SQL Planner!
How to restore the system with one click on Lenovo laptop
Detailed explanation of activity life cycle and startup mode
GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
【flask入门系列】Cookie与Session
Tutorial on the principle and application of database system (001) -- MySQL installation and configuration: installation of MySQL software (Windows Environment)
C language input / output stream and file operation
Principle of SSM framework
模板引擎Velocity 基础
SQL question brushing 586 Customers with the most orders
Red team Chapter 8: blind guess the difficult utilization process of the package to upload vulnerabilities
Redis 分布式鎖
UML tourism management system "suggestions collection"
Is the programmer's career really short?
How to optimize repeated if err in go language= Nil template code?
Sword finger offer II 015 All modifiers in the string
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
P2893 [USACO08FEB] Making the Grade G(dp&优先队列)
sql刷题586. 订单最多的客户