In Java, the StringTokenizer class separates strings, and the string class separates strings.

Source: Internet
Author: User
Tags stringtokenizer in java

In Java, the StringTokenizer class separates strings, and the string class separates strings.

This class is rarely used and is not recommended in the API documentation. RecommendedStringOfSplitMethod or java. util. regex package.

import java.util.StringTokenizer;public class StringTokenizerTest {    public static void main(String[] args) {        String str = "stay hungry , stay foolish .";        StringTokenizer st = new StringTokenizer(str," ");        while (st.hasMoreTokens()) {             System.out.print(st.nextToken()+" ");         }    }}

Split str output stay hungry, stay foolish.

 

The split method of String can also be used.

String[] temp = str.split(" ");        for (int i = 0; i < temp.length; i++) {            System.out.print(temp[i]+" ");        }

The output is also stay hungry and stay foolish.

 

Let's take a look at the differences between the nextToken () method of StringTokenizer and the split () method of String.

 

First look at the nextToken () method of StringTokenizer

Source code

public String nextToken() {    /*      * If next position already computed in hasMoreElements() and     * delimiters have changed between the computation and this invocation,     * then use the computed value.     */    currentPosition = (newPosition >= 0 && !delimsChanged) ?          newPosition : skipDelimiters(currentPosition);    /* Reset these anyway */    delimsChanged = false;    newPosition = -1;    if (currentPosition >= maxPosition)        throw new NoSuchElementException();    int start = currentPosition;    currentPosition = scanToken(currentPosition);    return str.substring(start, currentPosition);    }
 str.substring(start, currentPosition);

It can be seen that the string is intercepted based on location information.

 

Let's look at the split () method with String.

    public String[] split(String regex) {        return split(regex, 0);    }

Call

    public String[] split(String regex, int limit) {    return Pattern.compile(regex).split(this, limit);    }
public String[] split(CharSequence input, int limit) {        int index = 0;        boolean matchLimited = limit > 0;        ArrayList<String> matchList = new ArrayList<String>();        Matcher m = matcher(input);        // Add segments before each match found        while(m.find()) {            if (!matchLimited || matchList.size() < limit - 1) {                String match = input.subSequence(index, m.start()).toString();                matchList.add(match);                index = m.end();            } else if (matchList.size() == limit - 1) { // last one                String match = input.subSequence(index,                                                 input.length()).toString();                matchList.add(match);                index = m.end();            }        }        // If no match was found, return this        if (index == 0)            return new String[] {input.toString()};        // Add remaining segment        if (!matchLimited || matchList.size() < limit)            matchList.add(input.subSequence(index, input.length()).toString());        // Construct result        int resultSize = matchList.size();        if (limit == 0)            while (resultSize > 0 && matchList.get(resultSize-1).equals(""))                resultSize--;        String[] result = new String[resultSize];        return matchList.subList(0, resultSize).toArray(result);    }

The process of segmentation based on regular expressions is complicated.


Java delimiter

Public String f (String str, char del ){
String tem;
ArrayList <String> list = new ArrayList <String> ();
For (int I = 0; I <str. length; I ++ ){
Int index = str. indexOf (del );
Tem = str. substring (0, index );
If (! Tem. equals (""))
List. add (tem );
Str = str. substring (index + 1, str. length-(index + 1 ));
}
For (String s: list)
System. out. print (s );
}

What are the differences between String, StringBuffere, StringBuilder, and StringTokenizer in java?

String type
String class:
Java. lang. String class, which does not belong to eight basic data types. String is an object that represents a String constant.
Because the default value of an object is null, the default value of String is also null, but it is a special object and has features that other objects do not have.
Both new String () and new String ("") declare a new null String. Difference: the Null String is allocated with memory through the new operator, that is, it actually exists (defined ). Null is not (declared only). A null pointer exception is thrown when a null string is called.

Fundamentally Understand java. lang. String class and String pool.
1. The String class is final and cannot be inherited. Public final class String.
2. The essence of the String class is the character array char [], and its value cannot be changed. Private final char value [];
3. A String object has a special creation method. For example, String x = "abc"; "abc" indicates a String object, and x indicates the address of the "abc" object, it is called "abc" reference.
4. A String pool (String pool) is maintained during Java runtime. The String content in the String pool cannot be repeated, but the buffer pool does not exist for general objects (non-String classes, the created object is only used in the method stack.
5. There are three methods to create a string:
<1> use the new keyword to create a String, String s = new String ("abc ");
<2> directly specify String s = "abc ";
<3> Use concatenation to generate a new String, String s = "AB" + "c ";

Create a String object:
1. When using any method to create a String object s, JVM will use this object s to find whether there is a String object with the same content in the String pool. If it does not exist, a string s is created in the pool. Otherwise, it is not added in the pool.
2. in Java, if you use the new Keyword class to create an object, a new object will be created (in the heap or stack.
3. If you create a String object by specifying a String directly or using a String concatenation, the system only checks and maintains the String in the String pool. If no String exists in the pool, the system creates a String object in the pool, if yes, the existing String object address (reference) is directly returned ). This String object will never be created in the stack.
4. If you use an expression containing variables to create a String object, the system will not only check and maintain the String pool, but also create a String object in the stack area.

Immutable String:
The immutable string has a big difference: the compiler can set the string to be shared.
The String type cannot be changed. For example, if you want to change a String object, for example:
String s = "abc ";
S = "fuck ";
The JVM will not change the original object ("abc"), but will generate a new String object ("fuck", of course, first check whether there is a "fuck" String object in the String pool, if yes, reference it. If no, create it), and then let s point to it. If the original "abc" has no object to reference it, the garbage collection mechanism of the virtual machine will receive it. This improves the running efficiency!
Note: The comparison of string content in Java uses special methods such as equals and compareTo. = Compare whether the string references are the same.

Str ...... remaining full text>

Related Article

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.