aboutsummaryrefslogtreecommitdiff
path: root/project/JavaCommon/src/com/modulus/common/strings/Tokenizer.java
blob: 80363cd0f3688d3a24299b5c866495b8ce79ad77 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.modulus.common.strings;

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

/**
 * Class that tokenizes strings based on which groups
 * the characters fit into.
 * 
 * If the group is -1, then that tells the tokenizer to
 * not include those tokens and instead delete the characters
 * that belong to that group in the process of splitting.
 * 
 * @author jrahm
 *
 */
public abstract class Tokenizer {
	
	public String[] tokenize(String str){
		if(str.length() == 0)
			return new String[]{};
		
		List<String> tokens = new ArrayList<String>();
		StringBuffer buffer = new StringBuffer();
		
		int curGroup = groupOf(str.charAt(0));
		for(int i = 0;i < str.length();i++){
			char ch = str.charAt(i);
			
			int temp = groupOf(ch);
			if(temp != curGroup && curGroup != -1){
				curGroup = temp;
				tokens.add(buffer.toString());
				
				buffer = new StringBuffer();
			}
			
			if(temp != -1)
				buffer.append(ch);
		}
		tokens.add(buffer.toString());
		
		return tokens.toArray(new String[tokens.size()]);
	}
	
	public abstract int groupOf(char ch);
}