Java String Tokenize tokenize(String input, char by)

Here you can find the source of tokenize(String input, char by)

Description

Tokenizes a String by the specified character

License

Open Source License

Parameter

Parameter Description
input input string
by character to tokenize by

Return

list of strings

Declaration

public static List<String> tokenize(String input, char by) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**/*from   w  w w . j  av  a2  s.co  m*/
     * Tokenizes a String by the specified character
     *
     * @param input input string
     * @param by    character to tokenize by
     * @return list of strings
     */
    public static List<String> tokenize(String input, char by) {
        return tokenize(input, by, false);
    }

    /**
     * Tokenizes a String by the specified character, removing empty string if specified
     *
     * @param input       input string
     * @param by          character to tokenize by
     * @param removeEmpty should remove empty strings
     * @return list of strings
     */
    public static List<String> tokenize(String input, char by, boolean removeEmpty) {
        List<String> parts = new ArrayList<>();
        StringBuilder builder = new StringBuilder();
        char[] chars = input.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == by) {
                parts.add(builder.toString());
                builder.setLength(0);
                builder.trimToSize();
            } else {
                builder.append(c);
            }
            if (i == chars.length - 1) {
                parts.add(builder.toString());
                builder.setLength(0);
                builder.trimToSize();
            }
        }
        if (removeEmpty) {
            parts.removeIf(String::isEmpty);
        }
        return parts;
    }
}

Related

  1. tokenize(String formula)
  2. tokenize(String in)
  3. tokenize(String input)
  4. tokenize(String input)
  5. tokenize(String input)
  6. tokenize(String input, String delim)
  7. tokenize(String line)
  8. tokenize(String s)
  9. tokenize(String s)