String truncation to determine whether the string is equal or not and whether the string is null. Java, Android
Recently, when I was working on the Android project, I encountered a string truncation problem. I also knew whether the string is equal or not and whether the string is null. So I sorted it out and used it later, for your reference, can I share some better or other methods? Thank you!
1. The subSequence method can be used to intercept characters of any length.
For example:
String s = "AndroidandJava" System. out. println (s. subSequence (0, 1); the running result is: A. The original method is String. subSequence (beginIndex (number of starting bytes), endIndex (number of ending bytes ))
Ii. judge whether the strings are equal
Public class Test {public static void main (String [] args) {String a = "abcdef"; String B = "bcdef"; if (! A. equals (B) {System. out. print ("a is not equal to B");} else {System. out. print ("a equals B") ;}} the running result is: a is not equal to B
Note: Generally, equals is used to compare objects or strings, and = is used to compare values.
3. Four methods to determine whether a string is null:
Method 1: Compare the string length with high efficiency. It is the best method I know:
if(s == null || s.length() <= 0);
Method 2: The method is intuitive and convenient, but the efficiency is very low:
if(s == null ||"".equals(s));
Method 3: the method provided by Java SE 6.0 is almost the same as method 2. But for compatibility consideration, method 2 is recommended.
if(s == null || s.isEmpty());
Method 4: this is a simple and intuitive method with high efficiency, which is similar to method 2 and method 3:
if (s == null || s == "");
Note: s = null is necessary.
If the String type is null and the equals (String) or length () operation is performed, java. lang. NullPointerException is thrown.
And the s = null sequence must appear in the front, otherwise java. lang. NullPointerException will also be thrown.
The following Java code:
String str = null; if (str. equals ("") | str = null) {// an exception is thrown. System. out. println ("success ");}//"". equals (str); Make sure that no null error is returned.
You can give us some suggestions. Thank you!