How use String tokenizer java

How use String tokenizer java

Write a function, tokenize_string(input_string, delimiter_list) that returns a list of strings that are separated by the delimiters.
For example: tokenize_string(“How now, Mrs. Brown Cow”) returns [‘How’, ‘now’, ‘Mrs’, ‘Brown’, ‘Cow’]

Solution: Please have sample java program which shows how to tokenize string java:

package com.javahonk;

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

public class TokenizeString {

    public static void main(String[] args) {

        String string = "How now, Mrs. Brown Cow";
        char charArray[] = string.toCharArray();
        List<String> list = new ArrayList<String>();
        StringBuilder stringBuilder = new StringBuilder();
        int charLength = charArray.length;

        for (int i = 0; i < charLength; i++) {
            char c = charArray[i];

            if (c != ' ' && c != ',' && c != '.') {
                stringBuilder.append(c);
                if (i == charLength-1) {
                    list.add(stringBuilder.toString());
                }
            } else {
                if (!stringBuilder.toString().equals("")) {
                    list.add(stringBuilder.toString());
                    stringBuilder = new StringBuilder();
                }

            }

        }

        System.out.println(list);

    }

}

Output:
How use String tokenizer java

Leave a Reply

Your email address will not be published. Required fields are marked *