当前位置:网站首页>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
边栏推荐
- 制造业数字化转型究竟是什么
- Preliminary study on golang crawler framework
- C语言输入/输出流和文件操作
- EndeavourOS移动硬盘安装
- Leetcode 216 combined summation III -- backtracking method
- P2592 [ZJOI2008]生日聚会(dp)
- 【观察】数字化时代的咨询往何处走?软通咨询的思与行
- Stegano in the world of attack and defense
- Rhcsa Road
- [nodemon] app crashed - waiting for file changes before starting...解决方法
猜你喜欢
数据库系统原理与应用教程(002)—— MySQL 安装与配置:MySQL 软件的卸载(windows 环境)
sql刷题584. 寻找用户推荐人
Detailed explanation of activity life cycle and startup mode
OJ questions related to complexity (leetcode, C language, complexity, vanishing numbers, rotating array)
Leetcode 77 combination -- backtracking method
Installation and use of sqoop
制造业数字化转型究竟是什么
Alibaba cloud, Zhuoyi technology beach grabbing dialogue AI
Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)
VMware virtual machine failed during startup: VMware Workstation is incompatible with hyper-v
随机推荐
Go language source level debugger delve
如何使用phpIPAM来管理IP地址和子网
Flux d'entrées / sorties et opérations de fichiers en langage C
芯片供应转向过剩,中国芯片日产增加至10亿,国外芯片将更难受
判断链表是否是回文链表
The sharp drop in electricity consumption in Guangdong shows that the substitution of high-tech industries for high-energy consumption industries has achieved preliminary results
How to restore the system with one click on Lenovo laptop
Apple's self-developed baseband chip failed again, which shows Huawei Hisilicon's technological leadership
sql刷题584. 寻找用户推荐人
今天14:00 | 港大、北航、耶鲁、清华、加大等15位ICLR一作讲者精彩继续!
红队第10篇:coldfusion反序列化过waf改exp拿靶标的艰难过程
模板引擎Velocity 基础
OJ questions related to complexity (leetcode, C language, complexity, vanishing numbers, rotating array)
数据库系统原理与应用教程(003)—— MySQL 安装与配置:手工配置 MySQL(windows 环境)
Origin2018 installation and use (sorting)
How to use F1 to F12 correctly on laptop keyboard
嗨 FUN 一夏,与 StarRocks 一起玩转 SQL Planner!
vim用户自动命令示例
China carbon disulfide industry research and investment strategy report (2022 Edition)
VMware 虚拟机启动时出现故障:VMware Workstation 与 Hyper-v 不兼容...