一天一个类 --- StringTokenizer

这是一个将字符串按照指定的delimiters(分隔符)进行分割的类。

首先看看他的构造函数:

    public StringTokenizer(String str, String delim, boolean returnDelims) {
currentPosition = ;
newPosition = -;
delimsChanged = false;
this.str = str;
maxPosition = str.length();
delimiters = delim;
retDelims = returnDelims;
setMaxDelimCodePoint();
}
    public StringTokenizer(String str, String delim) {
this(str, delim, false);
}

默认是不返回delimiters的。

public StringTokenizer(String str) { this(str, " \t\n\r\f", false); }

这个是个默认的构造函数,其中使用的默认的delimiter是 " \t\n\r\f"

2、遍历边界 

    public boolean hasMoreTokens() {
/*
* Temporarily store this position and use it in the following
* nextToken() method only if the delimiters haven't been changed in
* that nextToken() invocation.
*/
newPosition = skipDelimiters(currentPosition);
return (newPosition < maxPosition);
}

查看是不是还有其他的分割串,这个通常作为遍历这个字符串是否结束的判断条件

3、获取每一个分割串

     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 >= && !delimsChanged) ?
newPosition : skipDelimiters(currentPosition); /* Reset these anyway */
delimsChanged = false;
newPosition = -; if (currentPosition >= maxPosition)
throw new NoSuchElementException();
int start = currentPosition;
currentPosition = scanToken(currentPosition);
return str.substring(start, currentPosition);
}

上面最后一句代码可以看出,使用的是字符串的一些操作,就是返回相应的字串。

这里还有一个特殊的方法,返回指定delimiter分割串

    public String nextToken(String delim) {
delimiters = delim; /* delimiter string specified, so set the appropriate flag. */
delimsChanged = true; setMaxDelimCodePoint();
return nextToken();
}

4、查看该字串串被分为了多少个字串

    public int countTokens() {
int count = ;
int currpos = currentPosition;
while (currpos < maxPosition) {
currpos = skipDelimiters(currpos);
if (currpos >= maxPosition)
break;
currpos = scanToken(currpos);
count++;
}
return count;
}

此时,如果没有指定delimiter的话,将会返回0

上一篇:HDU 5380 Travel with candy (贪心,单调队列)


下一篇:JavaScript 实现彩票中随机数组的获取