专栏首页WebJ2EESpring周边:StringTokenizer

Spring周边:StringTokenizer

图文无关

1. 什么是 StringTokenizer?

官方文档:

The string tokenizer class allows an application to break a string into tokens https://docs.oracle.com/javase/8/docs/api/java/util/StringTokenizer.html

注:StringTokenizer 是一个字符串分词工具。

构造函数:

public StringTokenizer(String str, String delim, boolean returnDelims){
    // An instance of StringTokenizer behaves in one of two ways, 
    // depending on whether it was created with the returnDelims flag 
    // having the value true or false:
    // 1. If the flag is false, delimiter characters serve to separate tokens. 
    //    A token is a maximal sequence of consecutive characters that are not delimiters.
    // 2. If the flag is true, delimiter characters are themselves considered to be tokens. 
    //    A token is thus either one delimiter character, 
    //    or a maximal sequence of consecutive characters that are not delimiters.
}
public StringTokenizer(String str, String delim) {
    this(str, delim, false);
}
public StringTokenizer(String str) {
    this(str, " \t\n\r\f", false);
}

注:参数【delim】中的每一个字符都是一个分隔符。

成员函数:

// Tests if there are more tokens available from this tokenizer's string.
public boolean hasMoreTokens() { ... }
// Returns the next token from this string tokenizer.
public String nextToken() { ... }

// Returns the same value as the hasMoreTokens method.
public boolean hasMoreElements() {return hasMoreTokens();}
// Returns the same value as the nextToken method, 
// except that its declared return value is Object rather than String.
public Object nextElement() {return nextToken();}

特别注意:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead. https://docs.oracle.com/javase/8/docs/api/java/util/StringTokenizer.html

JDK 已经不建议在新代码中使用 StringTokenizer 了,建议使用正则表达式功能替换;

2. Spring 对 StringTokenizer 的应用

org.springframework.util.StringUtils 源码节选:

  /**
   * Tokenize the given {@code String} into a {@code String} array via a
   * {@link StringTokenizer}.
   * <p>Trims tokens and omits empty tokens.
   * <p>The given {@code delimiters} string can consist of any number of
   * delimiter characters. Each of those characters can be used to separate
   * tokens. A delimiter is always a single character; for multi-character
   * delimiters, consider using {@link #delimitedListToStringArray}.
   * @param str the {@code String} to tokenize (potentially {@code null} or empty)
   * @param delimiters the delimiter characters, assembled as a {@code String}
   * (each of the characters is individually considered as a delimiter)
   * @return an array of the tokens
   * @see java.util.StringTokenizer
   * @see String#trim()
   * @see #delimitedListToStringArray
   */
  public static String[] tokenizeToStringArray(@Nullable String str, String delimiters) {
    return tokenizeToStringArray(str, delimiters, true, true);
  }

  /**
   * Tokenize the given {@code String} into a {@code String} array via a
   * {@link StringTokenizer}.
   * <p>The given {@code delimiters} string can consist of any number of
   * delimiter characters. Each of those characters can be used to separate
   * tokens. A delimiter is always a single character; for multi-character
   * delimiters, consider using {@link #delimitedListToStringArray}.
   * @param str the {@code String} to tokenize (potentially {@code null} or empty)
   * @param delimiters the delimiter characters, assembled as a {@code String}
   * (each of the characters is individually considered as a delimiter)
   * @param trimTokens trim the tokens via {@link String#trim()}
   * @param ignoreEmptyTokens omit empty tokens from the result array
   * (only applies to tokens that are empty after trimming; StringTokenizer
   * will not consider subsequent delimiters as token in the first place).
   * @return an array of the tokens
   * @see java.util.StringTokenizer
   * @see String#trim()
   * @see #delimitedListToStringArray
   */
  public static String[] tokenizeToStringArray(
      @Nullable String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {

    if (str == null) {
      return new String[0];
    }

    StringTokenizer st = new StringTokenizer(str, delimiters);
    List<String> tokens = new ArrayList<>();
    while (st.hasMoreTokens()) {
      String token = st.nextToken();
      if (trimTokens) {
        token = token.trim();
      }
      if (!ignoreEmptyTokens || token.length() > 0) {
        tokens.add(token);
      }
    }
    return toStringArray(tokens);
  }

StringUtils.tokenizeToStringArray 应用场景:

  • Spring 解析 Bean 的 name 、dependsOn 属性时,有应用:
// Bean 的 name 属性可以使用 ","、";"、" "作为分隔符。
public static final String MULTI_VALUE_ATTRIBUTE_DELIMITERS = ",; ";

@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
    // 获取 id 属性值
    String id = ele.getAttribute(ID_ATTRIBUTE);
    
    // 获取 name 属性值
    String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

    // 先将 name 属性值全部解析为 aliases
    List<String> aliases = new ArrayList<>();
    if (StringUtils.hasLength(nameAttr)) {
      String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
      aliases.addAll(Arrays.asList(nameArr));
    }

    // 若 id 属性值为空:
    // 将 name 属性的第一个值作为 beanName
    // 将 name 属性的其余值作为 aliases
    String beanName = id;
    if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
      beanName = aliases.remove(0);
      if (logger.isTraceEnabled()) {
        logger.trace("No XML 'id' specified - using '" + beanName +
            "' as bean name and " + aliases + " as aliases");
      }
    }
    
    ....
}

参考:

StringTokenizer Java Docs: https://docs.oracle.com/javase/8/docs/api/java/util/StringTokenizer.html

本文分享自微信公众号 - WebJ2EE(WebJ2EE)

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2019-10-09

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • IT兄弟连 Java Web教程 经典案例2

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    ITXDL
  • IT兄弟连 JavaWeb教程 JSTL标签的使用

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    ITXDL
  • IT兄弟连 Java语法教程 算符运算符

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    ITXDL
  • 年轻人的第一个自定义 Spring Boot Starter!

    陆陆续续,零零散散,栈长已经写了几十篇 Spring Boot 系列文章了,其中有介绍到 Spring Boot Starters 启动器,使用的、介绍的都是第...

    Java技术栈
  • IT兄弟连 JavaWeb教程 JSTL常用标签

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    ITXDL
  • IT兄弟连 JavaWeb教程 使用JSTL函数

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    ITXDL
  • IT兄弟连 Java Web教程 Servlet表单乱码问题

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    ITXDL
  • IT兄弟连 Java Web教程 ServletContext对象

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    ITXDL
  • 【大咖连载】服务设计与实现

    服务设计会影响到业务需求是否被正确、高效地实现,良好的服务设计能够帮助领域专家与开发人员之间,以及团队内部进行高效、准确的沟通。良好的实现则能缩短服务上线的周期...

    IT大咖说
  • IT兄弟连 Java Web教程 经典面试题2

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    ITXDL

扫码关注云+社区

领取腾讯云代金券