When comparing strings, you cannot simply compare with (int1 == int2)
like the int type.
When comparing strings, use one of the string methods, ** equals () **, instead of the comparison operator.
** equals () ** is extremely easy to use, just put the string you want to compare in the argument. For example, use it as follows.
if(String1.equals(String2)){
//The instruction you want to execute
}
When deciding the condition of the if statement, it is OK if you put String1.equals (String2)
in ().
After learning the equals () method, I will introduce regular expressions, their comparison methods, and how to extract strings.
A regular expression is a writing style used when you want to express a patterned character string. For example, it is used to express a zip code or credit card number.
For details on how to use it, see Regular expression basics for easy understanding.
If you want to compare variables using regular expressions, use matches ()
.
if(String1.matches(String2)){
//The instruction you want to execute
}
Usage is not much different from ʻequals () `.
If you want to retrieve a specific string, use substring ()
.
The first argument is the start index, which is the beginning of the string, and the second argument is the end index, which is the end of the string, plus a number.
String str = "AppleLemonApple";
String strget = str.substring(5,10); // Lemon
In this example, we are extracting the string Lemon
. In Java, the index starts at 0, so L is the 5th.
Recommended Posts