Recently do project Android encountered a string interception, to determine whether the string is equal and whether the string is empty problem just use on their own also know some, so tidy up convenient later use, and for everyone reference, what better method or other methods I can communicate together, thank you!
One, you can use the Subsequence method to intercept any length of characters
For example:
String s= "Androidandjava" System.out.println (s.subsequence (0, 1)); The result is: a The original method is: String.subsequence ( Beginindex (number of bytes started), EndIndex (end bytes))
Second, judge whether the string is 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 result of operation is: A is not equal to B
Note: Generally use the comparison object or string with equals, compare values with = =
Four ways to determine if a string is empty:
Method 1: Compare string lengths, high efficiency, is one of the best ways I know:
<span style= "FONT-SIZE:18PX;" >if (s = = NULL | | s.length () <= 0);</span>
Method 2: A method that most people use, intuitive, convenient, but inefficient:
<span style= "FONT-SIZE:18PX;" >if (s = = NULL | | "". Equals (s));</span>
Method 3:java SE 6.0 only begins to provide methods that are nearly equal in efficiency and method two, but for compatibility reasons it is recommended to use method two.
<span style= "FONT-SIZE:18PX;" > if (s = = NULL | | s.isempty ());</span>
Method 4: This is an intuitive, simple method, and the efficiency is very high, and the efficiency of method two or three is similar:
<span style= "FONT-SIZE:18PX;" >if (s = = NULL | | s = = "");</span>
Note: s = = null is necessary to exist.
If the String type is null, the Go to equals (string) or length () will throw java.lang.NullPointerException.
and the order of S==null must appear in front, otherwise it will also throw java.lang.NullPointerException.
The following Java code:
String str = NULL; if (Str.equals ("") | | Str= = = null) { //throws an exception System.out.println ("Success"); }//"". Equals (str); the rear ensures that no null error is encountered.
Everybody has the good thing to give the suggestion, thanks!
A method summarizing the truncation of strings, judging whether the strings are equal and whether the strings are empty java,android