Split () Replace () replaceall () function analysis in Java

Source: Internet
Author: User

This article is reproduced and transferred from:Http://feigme.iteye.com/blog/147259

Java. Lang. String split


The string split method is to directly split the string according to the given string, for example

    String value = "a,b,c,d,e";    String[] names = value.split(",");    for(int i=0,n=names.length;i    System.out.print(names[i]);    } 

Running result:

A B C D E

However, a problem occurs during IP resolution. The Code is as follows:

    String value = "209.242.1.1";    String[] names = value.split(".");    for(int i=0,n=names.length;i    System.out.print(names[i]+" ");    } 

The ideal output result should be 219 242 1, and nothing is output.

Very strange. Let's take a look at the split method signature.

    public String[] split(String regex) 

The parameter name here is RegEx
, That isRegular Expression(Regular expression ). This parameter is not a simple delimiter, but a regular expression:

    public String[] split(String regex, int limit) {    return Pattern.compile(regex).split(this, limit);    } 

Split
To directly call the split method of the matcher class. ".
The regular expression has a special meaning, so we must escape it when using it.

The modification code is as follows:

    String value = "209.242.1.1";    String[] names = value.split("\\.");    for(int i=0,n=names.length;i    System.out.print(names[i]+" ");    } 

Replace Method

First, let's take a look at the introduction of the replace method.

    String java.lang.String.replace(char oldChar, char newChar)    Returns a new string resulting from replacing all occurrences of oldChar in    this string with newChar.    If the character oldChar does not occur in the character sequence represented by    this String object, then a reference to this String object is returned. Otherwise,    a new String object is created that represents a character sequence identical to    the character sequence represented by this String object, except that every    occurrence of oldChar is replaced by an occurrence of newChar.    Examples:    "mesquite in your cellar".replace('e', 'o')    returns "mosquito in your collar"    "the war of baronets".replace('r', 'y')    returns "the way of bayonets"    "sparring with a purple porpoise".replace('p', 't')    returns "starring with a turtle tortoise"    "JonL".replace('q', 'x') returns "JonL" (no change)    Parameters:    oldChar the old character.    newChar the new character.    Returns:    a string derived from this string by replacing every occurrence of oldChar with newChar.

Usage:

    @Test    public void testReplace(){    String A = "aaa bCskd dkkAik kdaFe";    System.out.println(A.replace('a', '_'));    }

Result: ___ bcskd dkkaik kd_fe

This method is used to replace char characters and cannot process strings.
A. Replace ('aaa', '=') is incorrect.

However, A. Replace ("AAA", "=") is acceptable.

    @Test    public void testReplace(){    String A = "aaa bCskd dkkAik kaaaFe";    System.out.println(A.replace("aaa", "="));    }

Result: = bcskd dkkaik = Fe

It can be seen that replace ("", "") and method replaceall ("", "") have similar functions
Take a closer look at the difference

String java.lang.String.replace(CharSequence target, CharSequence replacement)Replaces each substring of this string that matches the literal target sequencewith the specified literal replacement sequence. The replacement proceeds fromthe beginning of the string to the end, for example, replacing "aa" with "b" inthe string "aaa" will result in "ba" rather than "ab".Parameters:target The sequence of char values to be replacedreplacement The replacement sequence of char valuesReturns:The resulting stringThrows:NullPointerException if target or replacement is null.Since:1.5

It's only available after 1.5.

But replaceall is more powerful.

    @Test    public void testReplace(){    String A = "aaa bCskd dkkAik kaaaFe";    System.out.println(A.replace(" ", ""));    } 

The result is aaabcskddkkaikkaaafe.
Replaceall can remove spaces inside the string
However, you cannot use the Replace ('','') method.
The Replace ("", "") method is optional.

Another point

    @Test    public void testReplace(){    String A = "aaa bCskd dkkAik kaaaFe";    System.out.println(A.replaceAll("[a-z]", "="));    } 

Result:
Replaceall can use regular expressions. It's powerful.
Let's look at the usage of replaceall in Java code.

    String java.lang.String.replaceAll(String regex, String replacement)    Replaces each substring of this string that matches the given regular expression    with the given replacement.    An invocation of this method of the form str.replaceAll(regex, repl) yields exactly    the same result as the expression    java.util.regex.Pattern. compile(regex).java.util.regex.Pattern.matcher(java.lang.CharSequence) matcher(str). replaceAll(repl)    See Also:    java.util.regex.Pattern    Parameters:    regex the regular expression to which this string is to be matched    Returns:    The resulting String    Throws:    PatternSyntaxException if the regular expression's syntax is invalid    Since:    1.4    @spec    JSR-51

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.