zoukankan      html  css  js  c++  java
  • Java StringTokenzier

    Java中substring方法可以分解字符串,返回的是原字符串的一个子字符串。如果要讲一个字符串分解为一个一个的单词或者标记,StringTokenizer可以帮你。

    1     public static void main(String[] args) {  
    2      StringTokenizer st = new StringTokenizer("www.baidu.com", ".b");  
    3      while(st.hasMoreElements()){  
    4      System.out.println("Token:" + st.nextToken());  
    5      }  
    6      }  

    输出:
    Token:www
    Token:baidu
    Token:com

    StringTokenizer有两个常用的方法:

    1.hasMoreTokens()。这个方法和hasMoreElements()方法的用法是一样的,只是StringTokenizer为了实现Enumeration接口而实现的方法,从StringTokenizer的声明可以看到:class StringTokenizer implements Enumeration<Object>。

    2.nextToken()。这个方法和nextElement()方法的用法是一样的,返回此 StringTokenizer 的下一个标记。

    StringTokenizer的三个构造方法:

    1.StringTokenizer(String str)。默认以” f”(前有一个空格,引号不是)为分割符。
    源码:

    /**
    * Constructs a string tokenizer for the specified string. The
    * tokenizer uses the default delimiter set, which is
    * <code>"&nbsp;&#92;t&#92;n&#92;r&#92;f"</code>: the space character,
    * the tab character, the newline character, the carriage-return character,
    * and the form-feed character. Delimiter characters themselves will
    * not be treated as tokens.
    *
    * @param str a string to be parsed.
    * @exception NullPointerException if str is <CODE>null</CODE>
    */
    public StringTokenizer(String str) {
    this(str, " f", false);

      public static void main(String[] args) {  
     
         StringTokenizer st = new StringTokenizer("www baidu com");  
         while(st.hasMoreElements()){  
         System.out.println("Token:" + st.nextToken());  
         }  
         } 
     
    

      输出:Token:www

                      Token:baidu

                      Token:com

    public static void main(String[] args) {  
     
      StringTokenizer st = new StringTokenizer("www.baidu.com", ".", true);  
     
      while(st.hasMoreElements()){  
     
      System.out.println("Token:" + st.nextToken());  
     
      }  
     
      }

    输出:Token:wwwToken:.Token:baiduToken:.Token:com

  • 相关阅读:
    vbs习题
    spotlight监控工具使用
    vue 不同路由同一个组件 缓存问题
    iphone手机上3D动画transform:rotateY闪现一下或者不显示
    vue 单独引用sass文件
    cnpm安装 npm安装node-sass报错
    webpack 打包css时提示Unexpected character '@'
    window下npm启动报错This is probably not a problem with npm. There is likely additional logging output above.
    HBuilder 配置android模拟器
    windows 切换git远程仓库地址后 git push 提示Authentication failed
  • 原文地址:https://www.cnblogs.com/Firesun/p/9430372.html
Copyright © 2011-2022 走看看