Java方法总结与源码解析(未完待续)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java方法总结与源码解析(未完待续),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2229字,纯文字阅读大概需要4分钟。
内容图文
使用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); } privateint skipDelimiters(int startPos) { if (delimiters == null) thrownew 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方法。
原文:http://www.cnblogs.com/yangsy0915/p/5426049.html
内容总结
以上是互联网集市为您收集整理的Java方法总结与源码解析(未完待续)全部内容,希望文章能够帮你解决Java方法总结与源码解析(未完待续)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。