当前位置:网站首页>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
边栏推荐
- 复杂度相关OJ题(LeetCode、C语言、复杂度、消失的数字、旋转数组)
- Detailed explanation of activity life cycle and startup mode
- Example of vim user automatic command
- Tutorial on the principle and application of database system (005) -- Yum offline installation of MySQL 5.7 (Linux Environment)
- Go language source level debugger delve
- 【直播预约】数据库OBCP认证全面升级公开课
- EndeavourOS移动硬盘安装
- 免费抽奖 | 《阿巴豆》探索未来系列盲盒数字版权作品全网首发!
- P2592 [zjoi2008] birthday party (DP)
- Apple's self-developed baseband chip failed again, which shows Huawei Hisilicon's technological leadership
猜你喜欢
Building blocks for domestic databases, stonedb integrated real-time HTAP database is officially open source!
数据库系统原理与应用教程(002)—— MySQL 安装与配置:MySQL 软件的卸载(windows 环境)
Detailed explanation of activity life cycle and startup mode
接口测试框架中的鉴权处理
Installation and use of sqoop
How to use MySQL language for row and column devices?
How to maintain the laptop battery
游戏行业安全选择游戏盾,效果怎么样?
Redis6.0 新功能
你还在用收费的文档管理工具?我这有更牛逼的选择!完全免费
随机推荐
模板引擎Velocity 基础
Hi Fun Summer, play SQL planner with starrocks!
Germany if was crowned with many awards. How strong is this pair of headphones? In depth evaluation of yinpo GTW 270 hybrid
求求你们,别再刷 Star 了!这跟“爱国”没关系!
Rhcsa Road
Rhcsa Road
Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)
AI college entrance examination volunteer filling: the gods of Dachang fight, and candidates pay to watch
EndeavourOS移动硬盘安装
Exclusive news: Alibaba cloud quietly launched RPA cloud computer and has opened cooperation with many RPA manufacturers
sql刷题1050. 合作过至少三次的演员和导演
Défaillance lors du démarrage de la machine virtuelle VMware: le poste de travail VMware n'est pas compatible avec hyper - V...
How to cancel automatic search and install device drivers for laptops
How to solve the keyboard key failure of notebook computer
Sqlserver query: when a.id is the same as b.id, and the A.P corresponding to a.id cannot be found in the B.P corresponding to b.id, the a.id and A.P will be displayed
复杂度相关OJ题(LeetCode、C语言、复杂度、消失的数字、旋转数组)
SQL question brushing 586 Customers with the most orders
Are you still using charged document management tools? I have a better choice! Completely free
Kali install Nessus
How to restore the system with one click on Lenovo laptop