Common methods of String in Java (i)

Source: Internet
Author: User

The previous article introduces several common construction methods in string, which are emitted by the core object of string, such as the encoding of characters, the byte expression of characters, the effect on GC, regular expression, pattern matching, which is probably the most abundant object in Java. Let's talk about some of the common methods defined in the API today.

1. Length method

Length ()
Returns the length of the sequence of characters represented by this object.

Returns the length of the string (or interpreted as the length of the corresponding character array), or throws a null pointer exception (JAVA.LANG.NULLPOINTEREXCEPTION) If the value of the string object is null.

String str = "Hello, google!" "=" Hello, google! " ; System.out.println (Str.length ()); System.out.println (Str1.length ());

The result of the operation is:

614

2. IsEmpty method

public boolean isEmpty ()
Returns true if Length () is 0, otherwise false.

Returns true if the length of the string is 0, otherwise false is returned.

Throws a null pointer exception (JAVA.LANG.NULLPOINTEREXCEPTION) If the value of the string object is null.

Note: Because in the process of using, you will forget that the string value is null, and all the judging string is empty try to use several methods encapsulated in Org.apache.commons.lang.StringUtils:

1) IsEmpty method

The source code is as follows:

 Public Static Boolean isEmpty (String str) {  returnnull | | str.length () = = 0;}

2) Isnotempty method

The source code is as follows:

 Public Static Boolean isnotempty (String str) {  return ! stringutils.isempty (str);}

3) IsBlank method

The source code is as follows:

 Public Static BooleanIsBlank (String str) {intStrLen; if(str = =NULL|| (StrLen = Str.length ()) = = 0) {return true; } for(inti = 0; i < StrLen; i++) {if((Character.iswhitespace (Str.charat (i) = =false)) {return false; }}return true;}

4) Isnotblank method

The source code is as follows:

 Public Static Boolean Isnotblank (String str) {  return ! Stringutils.isblank (str);}

3. CharAt method

charAt (int index)
Returns the char value at the specified index. An index ranges from 0 to length ()-1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

Throws:
Indexoutofboundsexception-if The index argument is negative or not less than the length of this string.

The character that returns the index position (String itself is char[] array type)

argument is int index, range from 0 to length ()-1

If the index is negative or greater than or equal to the length of the string, the index out-of-bounds exception indexoutofboundsexception is thrown.

String str = "Hello, google!" ; System.out.println (Str.charat (0-1));

Operation Result:

h!

4. GetByte method

GetBytes ()
Encodes this String to a sequence of bytes using the platform ' s default charset, storing the result into a new byte arra Y.

GetBytes (Charset Charset)
Encodes this String to a sequence of bytes using the given charset, storing the result into a new byte array.

Each of the two methods returns an array of byte types that correspond to the string (specified encoding).

return New String (Str.getbytes ("iso-8859-1"), "UTF-8");

5. Equals method

Equals (Object AnObject)
Compares this string to the specified object.

Compare two objects whether the content is equal, words do not say, directly on the classic code implementation:

Constants are usually placed in front, and variables are placed behind

String str = "Hello, google"; if ("Hello, Baidu". Equals (str)) {SYSTEM.OUT.PRINTLN ("Is you kidding me?")  Else  {System.out.println ("It ' s ok!" );}

Output Result:

It ' s ok!

6. CompareTo method

CompareTo (String anotherstring)
Compares strings lexicographically.

Compares two strings in a dictionary order, returns 0 for equality, returns a value less than 0 in front of anotherstring, or returns a value greater than 0.

String str = "Hello, google"; System.out.println ("Compare with Baidu:" + str.compareto ("Hello, Baidu"));

Output Result:

Compare with Baidu:5

The method is applied to the implementation of the comparer in Java (both internal and external), and the knowledge is read: Java_ two comparator implementations.

PS: External comparators can be simpler to implement with anonymous inner classes, or lambda expressions in java8 are simpler, see for lambda Knowledge: Java8 First Experience (i) lambda expression syntax

7. StartsWith method and EndsWith method

StartsWith (String prefix)
Tests If this string starts with the specified prefix.

StartsWith (String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with the specified prefix.

EndsWith (String suffix)
Tests If this string ends with the specified suffix.

Determines whether a string has the beginning or end of a given string ( the argument can only be a string, and regular expressions are not supported )

String str = "Hello, google"; System.out.println (Str.startswith ("Google", 7));

Output Result:

True

8. Hashcode method

Returns a hash code for this string.

Returns the hash value of the string that, when initializing the object, overrides the Equals () and Hashcode () methods based on the property to compare if the object is likely to be compared.

9. IndexOf method and LastIndexOf method

indexOf (int ch)
Returns the index within this string of the first occurrence of the specified character.

indexOf (int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the Specif IED index.

IndexOf (String str)
Returns the index within this string of the first occurrence of the specified substring.

IndexOf (String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

lastIndexOf (int ch)
Returns the index within this string of the last occurrence of the specified character.

lastIndexOf (int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the Specified index.

LastIndexOf (String str)
Returns the index within this string of the last occurrence of the specified substring.

LastIndexOf (String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the Specified index.

is the index value (int) returned, or is it intuitive to see the graph:

String str = "Hello, google"; System.out.println ("The second G ' s index is:" + str.indexof (103, 8)); System.out.println ("Google's index is:" + str.indexof ("Google"));

Output Result:

G ' s index is:10google ' s index is:7

10. Substring method

substring (int beginindex)
Returns a string, a substring of this string.

substring (int beginindex, int endIndex)
Returns a string, a substring of this string.

This method is estimated to use the highest frequency, separating the string method, will throw the index out of bounds exception.

String str = "Hello, google"; System.out.println (Str.substring (0, 5));

Output Result:

Hello

Remember one thing: front closed and open [Beginindex, EndIndex]

Thanks Bing search: https://cn.bing.com/

Common methods of String in Java (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.