Home> Java> javaTutorial> body text

Quickly get started with Java data structure strings

WBOY
Release: 2022-05-16 12:03:36
forward
1965 people have browsed it

This article brings you relevant knowledge aboutjava, which mainly introduces related issues about strings. A string is a limited sequence composed of zero or more characters, also known as String, let’s take a look at it, I hope it will be helpful to everyone.

Quickly get started with Java data structure strings

Recommended study: "java video tutorial"

1. Basic knowledge of strings

A string is a limited sequence of zero or more characters, also known as a string.

We can know from this basic concept:

  • Zero or more Composed of characters: indicates that the internal element type of the string is characters.
  • Limited: It means that the content length of the string is limited, less than a maximum range, but within this range, the actual length is uncertain.
  • Sequence: It shows that there is a predecessor and successor relationship between adjacent characters in the string.

There is no built-in string type in Java. Each string enclosed in double quotes is an instance of the String class in Java.

That is to say, String is not a data type in Java. All strings in Java are instances of String. object.

String in Java

The String class in Java represents a string, and all string literals (such as "abc") in Java programs are Instances of this class.

In other words, all double-quoted strings in Java programs are objects of the String class.String class is under the java.lang package, so there is no need to import the package when using it!

The most important feature of String in Java is:

The String class is immutable, so once you create a String object, its value cannot be changed. . We call this property immutability of String.

Immutability of strings

Immutability: When you reassign a value to a string, the old value is not destroyed in the memory, but a new space is created to store the new value.

That is to say, once a String object is created in memory, it will be immutable.All methods in the String class do not change the String object itself, but recreate a new String object.

For example:

String s="dcm";String s="ddccmm"
Copy after login

When the value of s changes, the value of ddccmm does not cover dcm. It just develops a new space to store ddccmm and points s to it.

If we traverse, assign and modify a string containing a large number of characters in actual development, many string objects that cannot be released will be generated in the memory, causing memory garbage.

Because of the immutability of the String object, if you need to make a large number of modifications to the string, add characters, delete characters, etc., try not to use the String object, because this will frequently create new objects and cause the execution of the program. Efficiency decreases.

At this time we can use another string class StringBuilder in Java.

When we do questions, we generally use the String class for strings, but considering that we sometimes use the StringBuilder class, I will explain the StringBuilder class in a little more detail.

2.StringBuilder class

StringBuilderis avariablestring class, we can think of it as a container , the variable here means that the content in theStringBuilder object is variable.

2.1 Commonly used methods of the StringBuilder class
Quickly get started with Java data structure strings
It can be seen that to construct an object ofStringBuilder, you can only use its Construct method to construct, unlikeStringwhich can be created directly withString s= "123"

because theStringBuilderclass object is variable , so when we need to make a lot of changes to a string, it is generally defined as theStringBuilderclass.

2.2 The difference between String and StringBuilder

StringObjects are immutable. Each time you use one of the methods in theStringclass, a new string object is created in memory, which requires new space to be allocated for the new object.

StringBuilderThe object is a dynamic object that allows the number of characters in the string it encapsulates to be expanded, but you can specify a value for the maximum number of characters it can hold when modifyingStringBuilder, it will not reallocate space for itself until capacity is reached. When capacity is reached, new space is automatically allocated and capacity is doubled. That is to say, when the string is changed, the state of the current object is updated.

The capacity of theStringBuilderclass can be specified using one of the overloaded constructors.

2.3 Conversion between String class and StringBuilder class

Conversion of String class into StringBuilder class

public class String{ public static void main(String[] args){ String s = "baibai"; StringBuilder s1 = new StringBuilder(s); System.out.println(s1); }}
Copy after login

StringBuilder Convert the class to the String class

public class String { public static void main(String[] args){ StringBuilder s1 = new StringBuilder(); //连续连接 s1.append("abc").append("efg"); String s = s1.toString(); System.out.println(s); }}
Copy after login

3. Initialize the String class

3.1 Two ways to initialize the String object:

//方法一:直接创建 String s1= "大聪明 超牛的"; //方法二:对象创建 String s2 = new String("大聪明 超牛的"); String s3 = new String();//也可以创建一个空串
Copy after login

Although both The methods look the same but are essentially different.
Strings created by String are stored in the public pool, while string objects created by new are on the heap. Is there any difference between storing it in the public pool (constant pool) and the heap?

Let’s give an example:

String s1 = "大聪明 超牛的"; // String 直接创建 String s2 = "大聪明 超牛的"; // String 直接创建 String s3 = s1; // 相同引用 String s4 = new String("大聪明 超牛的"); // String 对象创建 String s5 = new String("大聪明 超牛的"); // String 对象创建 System.out.println(System.identityHashCode(s1)); System.out.println(System.identityHashCode(s2)); System.out.println(System.identityHashCode(s3)); System.out.println(System.identityHashCode(s4)); System.out.println(System.identityHashCode(s5));
Copy after login

Output:
Quickly get started with Java data structure strings
It can be seen that the addresses of the first three strings are the same, and the addresses of the last two are the same. Are not the same!

This is because when you create a string directly, you will first find out if there is such a string in the public pool. If there is, then point the reference directly to it without developing a new space. Here, the three references of s1, s2, and s3 point to the same memory in the public pool.

When an object is created, new space will be opened on the heap to store strings every time. That is to say, s4 and s5 respectively point to two different pieces of memory on the heap, but inside these two pieces of memory All store the same things.

4. Commonly used APIs for the String class

Let me emphasize again that when we encounter string-related questions when doing questions, we almost always use the String class to solve problems, except for characters. We may temporarily use the StringBuilder class when making a large number of changes to the string.

The temporary thing here is that we generally need to convert the string into the String class after operations such as changing the string.

So the API we want to learn is mainly the String class API. Corresponding to the API of StringBuilder, we only need to learn the two mentioned above.

String class is under the java.lang package, so there is no need to import the package when using it!

4.1 Convert basic data types into strings

There are three ways:

(1)基本类型数据的值+“” (最常用,最简单);
(2)使用包装类中的静态方法static String toString(int i)返回一个表示指定整数的String 对象。如:在Integer中:Integer.toString(6)
(3)使用String类中的静态方法static String valueOf(int i)返回int 参数的字符串表示形式。如:String.valueOf(6)

String 类别中已经提供了将基本数据型态转换成String 的 static 方法也就是 String.valueOf() 这个参数多载的方法 :

String.valueOf(boolean b) //将 boolean 变量 b 转换成字符串 String.valueOf(char c) //将 char 变量 c 转换成字符串 String.valueOf(char[] data) //将 char 数组 data 转换成字符串 String.valueOf(char[] data, int offset, int count) //将char数组data中由data[offset]开始取 count个元素转换成字符串 String.valueOf(double d) //将 double 变量 d 转换成字符串 String.valueOf(float f) //将 float 变量 f 转换成字符串 String.valueOf(int i) //将 int 变量 i 转换成字符串 String.valueOf(long l) //将 long 变量 l 转换成字符串 String.valueOf(Object obj) //将 obj 对象转换成 字符串, 等于 obj.toString()
Copy after login

因为是静态方法所以不需要实例化。

4.2 字符串转换为基本数据类型

一般使用包装类的静态方法parseXX("字符串")

要将 String 转换成基本数据类型大多需要使用基本数据型态的包装类别,如:String 转换成 byte可以使用Byte.parseByte(String s)

Byte.parseByte(String s) //将 s 转换成 byte Byte.parseByte(String s, int radix) //以 radix 为基底 将 s 转换为 byte Double.parseDouble(String s) //将 s 转换成 double Float.parseFloat(String s) //将 s 转换成 float Integer.parseInt(String s) //将 s 转换成 int Long.parseLong(String s) //将 s 转换成 long
Copy after login

注意这里也是静态方法,只不过都是对应包装类的静态方法

4.3 使用length()得到一个字符串的字符个数

int len = String.length();
Copy after login

4.4 使用toCharArray()将一个字符串转换成字符数组

Char[] arr = String.toCharArray();
Copy after login

4.5 判断两个字符串的内容是否相等返回true/false

String1.equals(String2);//区分大小写 String1.equalsIgnoreCase(String2);//不区分大小写
Copy after login

4.6 与位置相关的字符串

charAt(int)//得到指定下标位置对应的字符 indexOf(String)//得到指定内容第一次出现的下标 lastIndexOf(String)//得到指定内容最后一次出现的下标
Copy after login

4.7 将一个字符串按照指定内容劈开split(String),返回字符串数组。

String s = "wa,dcm,nb!"; String[] str = s.split(",");//返回结果中str[1]=dcm
Copy after login

4.8contains(String)判断一个字符串里面是否包含指定的内容,返回true/false

Boolean a = String1.contains(String2)
Copy after login

4.9 使用substring()截取字符串,返回子串

String.substring(int)//从指定下标开始一直截取到字符串的最后 String.substring(int,int)//从下标x截取到下标y-1对应的元素
Copy after login

4.10 字符串大小写转换

String.toUpperCase() //将一个字符串全部转换成大写 String.toLowerCase()//将一个字符串全部转换成小写
Copy after login

4.11 使用replace()进行字符串内容替换

String.replace(String,String) //将某个内容全部替换成指定内容 String.replaceAll(String,String) //将某个内容全部替换成指定内容,支持正则 String.repalceFirst(String,String) //将第一次出现的某个内容替换成指定的内容
Copy after login

5.字符串进阶练习

387. 字符串中的第一个唯一字符
Quickly get started with Java data structure strings
题解:

把字符串的单个字符转化为对应数组下标,遍历一遍字符串获得26个字母分别出现几次。然后在遍历一遍字符串看哪个字符先出现次数为1,就输出对应下标。

class Solution { public int firstUniqChar(String s) { int len = s.length(); int[] vis = new int[26]; int temp = -1; for(int i = 0; i 

或者我们也可以把字符串先转换为字符数组来解题,原理都是一样的!

class Solution { public int firstUniqChar(String s) { int[] arr = new int[26]; char[] chars = s.toCharArray(); for (int i = 0; i 

推荐学习:《java视频教程

Copy after login

The above is the detailed content of Quickly get started with Java data structure strings. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!