Chapter 4 Java Strings

One, string

character( char) Type is one of the basic data types of Java, used to store a single character. In the development process, multiple characters can often express a meaningful data. Java providesString( String) Type, used to deal with a series of characters. A string is a sequence of several characters.

1.1, the declaration and initialization of the string

Syntax format:

String  变量名 = “初始值”
或者
String 变量名 = new string(“初始值”);

example:

String str1 = "Hello world";
String str2 = new String("Hello World");

1.2. String connection

The " +" operator can be used to concatenate strings, and can also concatenate strings and basic data types.
example:

Public class Text {
    
    
	Public static void main(String[] args){
    
    
		String str1 = “Hello”;
		String str2 = “Java”;
		String str3 = “Hello Java”;
		String str4 = “Hello” + “Java”;
		String str5 = str1 + str2;
		Int num = 520;
		String str6 = num + str2;
		System.out.println(“str1 =+str1);
		String.out.println(“str2 =+str2);
		System.out.println(“str3 =+str3);
		System.out.println(“str4 =+str4);
		System.out.println(“str5 =+str5);
		System.out.println(“str6 =+str6);
	}
}

注意: There are no spaces in the strings concatenated with the "+" operator.

1.3, string comparison

Example:

Public class Text{
    
    
	Public static void main(String[] args){
    
    
		String str1 = "Hello";
		String str2 = "Hello";
		String str3 = new String("Hello");
		System.out.println("(str1 == str2) = " + (str1 == str2));
		System.out.println("(str1 == str3) = " + (str1 == str3));
		System.out.println("str1.equals(str3) = " + str1.equals(str3));
	}
}

Explanation:

  1. The " ==" operator is used to compare the content stored in the variable (data or memory address number). Since the string is a reference data type, if
    the result of str1 == str2 is true, it means that the same memory address number is stored in the two variables str1 and str2, that is, the same block of memory is referenced.
  2. The equals() method provided by the String type compares whether the literal value of the string is the same.
  3. The value of "str1 == str2" is true, because the memory address numbers of str1 and str2 are the same, but str3 has applied for a new memory address, so
    the value of "str1 == str3" is false.

1.4, the storage of strings

字符串是引用数据类型, So the string is stored inheapMedium (string pool in the heap). In order to save memory, when executing each string, it will first look for the existence of the defined string in the string pool, if it exists, apply it directly, if it does not exist, it will reallocate the memory to store the string.

1:String str1 = "Hello";
2:String str2 = "Hello";
3:String str3 = new String("Hello");

When program 1 is executed, it will look for the existence of "Hello" in the string pool, and if it does not exist, allocate memory to store the string "Hello"; when executing program 2, it will still look for the existence of "Hello" in the string pool. Because "Hello" exists, the memory address number of str1 is quoted and stored in the stack; when program 3 is executed, although the string "Hello" exists in the string pool, it has applied for a new block in the string pool. In the memory, a new memory number is generated, and then the new number is stored in the stack.

2. Commonly used APIs for strings

2.1、API

APIApplication Programming Interface), that is, the application programming interface.

  1. AApplication), that is, the application, according to different occasions, it can be a software that provides specific functions, a network service that provides certain data, a class library as a program component, or even a hardware device, etc.
  2. PProgramming), namely programming.
  3. IInterface), the interface, is the part where different systems or entities are handed over and interact with each other through it.

注意: API is the part where other entities or systems exchange information with our program during the programming process.

2.2, commonly used API

Serial number Method name Return type effect
1 equals(Object anObject) boolean Compare this string with the specified object
2 equalsIgnoreCase(String anotherString) boolean Ignore case and compare whether the literal values ​​of two strings are equal
3 length() int Get the length of the string
4 charAt(int index) char Get the char value at the specified index
5 indexOf(String str) int Get the index of the first occurrence of the specified subcharacter/string in the original string (if the string does not contain the character, the return value is -1.)
6 lastIndexOf(String str) int Get the index of the rightmost occurrence of the specified subcharacter/string in the original string
7 startsWith(String prefix) boolean Test whether the original string starts with the specified prefix
8 endsWith(String suffix) boolean Test whether the original string ends with the specified suffix
9 toLowerCase() String Get the lowercase string corresponding to the original string
10 toUpperCase() String Get the uppercase string corresponding to the original string
11 toCharArray() String[] Use str.toCharArray() to convert a string to an array
12 substring(int beginIndex) String Intercept the original string, start intercepting from the position where the parameter beginIndex is the subscript)
13 substring(int beginIndex, int endIndex) String Intercept the original string from the position where the parameter beginIndex is the subscript to the position where the parameter endIndex is the subscript. str.substring(num1,num2)
14 trim() String Remove the spaces at the beginning and end of the original string
15 split(String regex) String[] Split the original string into an array of strings according to the incoming parameter regex (note: the regex parameter generally uses regular expressions)
16 replace(String regex, String replacement) String Replace the specified content in the original string with another content

2.3, control symbol

The control character is to control the format of the output result.

Serial number Format specifier Description
1 %s String type
2 %c Character type
3 %b Boolean type
4 %md Integer type (decimal)
5 %x Integer type (hexadecimal)
6 %The Integer type (octal)
7 %m.nf Floating point type
8 %t Tabs
9 \n Newline

注意:m is the number of columns occupied by the output result, and n is the number of digits after the decimal point of the floating point type;

Three, string and basic data type conversion

3.1, the basic data type is converted to String type

There are usually two ways to convert basic types of data into string types:

  1. +Convert the basic type to string type through string connection (using the " " symbol);
  2. bystringThe vlalueof(basic type data variable name) method provided by the type converts the basic data type to a string type.

Example 1:

Pubic class Text{
    
    
Public static void mian(String[] args){
    
    
//通过字符串连接将基本类型转换为String型。
Int num = 2020;
Boolean bool = true;
String str1 ="" + num;
String str2 = "" + bool;
}
}

Example 2:

Public class Text {
    
    
Public static void main(String[] args){
    
    
//通过string类型提供的vlalueof(基本数据类型 变量名)方法将基本数据类型转换为字符串类型。
Int num = 2020;
Boolean bool = true;
String str1 = string.vlalueOf(num);
String str2 = string.vlalueOf(bool);
}
}

3.2, String type is converted to basic data type

Convert string type to basic type, You need to use basic types of packaging. Java provides a corresponding packaging class for each basic type, and the packaging class provides some common operations, including converting string types into basic types. The basic types of packaging classes and their conversion methods are as follows:

basic type Packaging Method name effect
byte Byte parseByte(String s) 将字符串转换为byte类型
short Short parseShort(String s) 将字符串转换为short类型
int Integer parseInt(String s) 将字符串转换为int类型
long Long parseLong(String s) 将字符串转换为long类型
float Float parseFloat(String s) 将字符串转换为float类型
double Double parseDouble(String s) 将字符串转换为double类型
boolean Boolean parseBoolean(String s) 将字符串转换为boolean类型

解释;
字符串与char类型的转换可以通过字符串的charAt(int index )方法来实现。

注意:
1、Integer与int的区别

  1. Integer是int的包装类,int则是java的一种基本数据类型
  2. Integer变量必须实例化后才能使用,而int变量不需要
  3. Integer实际是对象的引用,当new一个Integer时,实际上是生成一个指针指向此对象;而int则是直接存储数据值 。
  4. Integer的默认值是null,int的默认值是0

int 是基本数据类型
Integer是其包装类,注意是一个类。

2、为什么要提供包装类呢???
一是为了在各种类型间转化,通过各种方法的调用。否则 你无法直接通过变量转化。
比如,现在int要转为String

int a=0;
String result=Integer.toString(a);

在java中包装类,比较多的用途是用在于各种数据类型的转化中。
我写几个demo

//通过包装类来实现转化的

int num=Integer.valueOf("12");
int num2=Integer.parseInt("12");

double num3=Double.valueOf("12.2");
double num4=Double.parseDouble("12.2");

//其他的类似。通过基本数据类型的包装来的valueOf和parseXX来实现String转为XX

String a=String.valueOf("1234");//这里括号中几乎可以是任何类型
String b=String.valueOf(true);
String c=new Integer(12).toString();//通过包装类的toString()也可以
String d=new Double(2.3).toString();

再举例下。比如我现在要用泛型

List<Integer> nums;

这里<>需要类。如果你用int。它会报错的
例1:

Public class Text {
    
    
	Public static void main(String[] args){
    
    
		String str1 =2020;
		String str2 =3.14;
		String str3 =true;
		Int num = integer.parseInt(str1);
		Double doub = double.parseDouble(str2);
		Boolean bool = boolean.parseBoolean(str3);
	}
}

例2:

Public class Text {
    
    
	Public static void main(String[] args){
    
    
		String  str =2020年新春快乐。”;
		Char char =str.charAt(4);
		}
}

Guess you like

Origin blog.csdn.net/Bennettgxd/article/details/113193663