使用StringTokenizer去掉字符串中的空格
public class StringTo { public static void main(String[] args){ String text = " We are students "; System.out.println("源字符串是:"); System.out.println(text); System.out.println(text.trim()); StringTokenizer st = new StringTokenizer(text," "); StringBuffer sb = new StringBuffer(); int i = 1; while(st.hasMoreTokens()){ i++; sb.append(st.nextToken()); } System.out.println("去掉字符串中所有空格之后的字符串是:"); System.out.println(sb.toString()); } }
主要是通过st.hasMoreTokens实现的去除空格,那么我们观察下源码:
public StringTokenizer(String str, String delim, boolean returnDelims) {
currentPosition = 0;
newPosition = -1;
delimsChanged = false;
this.str = str;
maxPosition = str.length();
delimiters = delim;
retDelims = returnDelims;
setMaxDelimCodePoint();
}
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); } private int skipDelimiters(int startPos) { if (delimiters == null) throw new NullPointerException(); int position = startPos; while (!retDelims && position < maxPosition) { if (!hasSurrogates) { char c = str.charAt(position); if ((c > maxDelimCodePoint) || (delimiters.indexOf(c) < 0)) break; position++; } else { int c = str.codePointAt(position); if ((c > maxDelimCodePoint) || !isDelimiter(c)) { break; } position += Character.charCount(c); } } return position; }
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);
}
源码通过获取字符串的长度,遍历每个字符,将传入的字符进行比较,如果与需要截取的字符相同,则调用substring方法。