Substring (a, B ))
String greeting = "hello ";
System. Out. println (greeting. substring (0, 3); // el
The second parameter of the substring method is the first location that you do not want to copy. Here we will copy 0, 1, and 2 characters.
This method has the following advantages: it is easy to calculate the length of a substring. For example, the length of S. substring (A, B) is B-.
Splicing
Like most programming languages, Java allows the use of the plus sign to connect two strings.
String st1=“hello”;
String st2="world";
System.out.println(st1+st2);//helloworld
Immutable string
The string class does not provide a method to modify the string. If you want to change the greased content to "help", you cannot directly change the last two characters to P (strings are constant; their values cannot be changed after they are created .).
Checks whether the string is equal.
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true
if and only if the argument is not null
and is a String
object that represents the same sequence of characters as this object.
public boolean equalsIgnoreCase(String anotherString)
This method can be used to check whether two strings are equal and case-insensitive.
Compares this String
to another String
, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.
You cannot use = to check whether two strings are equal! This operator can only determine whether two strings are placed in the same position. Of course, if strings are placed in the same position, they must be equal. However, it is entirely possible to copy multiple strings with the same content to different locations.
String greeting="Hello";/initialize greeting to a string
if(greeting=="Hello")
//probably true
if(greeting.substring(0,3)=="Hel")
//probably false
If the virtual machine always shares the same string, you can use the = Operator to check whether it is equal. In fact, only string constants are shared, and the results produced by operations such as + or substring are not shared. Therefore
Do not use the = Operator to test the equality of strings to avoid bad bugs in the program. It indicates that such a bug is similar to a random intermittent error.