Implement String Tokenizer
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-05-02
Problem Statement
Design a String Tokenizer class/module that can parse strings into tokens based on delimiters. The focus is on object-oriented design, modularity, and handling edge cases like multiple delimiters, empty tokens, and escape characters.
✅ Functional Requirements
1.Basic Tokenization
•Split a string into tokens based on one or more delimiters.
•Support returning tokens one by one (iterator-like interface).
2.Advanced Tokenization Options
•Option to ignore empty tokens or include them.
•Support custom delimiters (single character or set of characters).
•Optional: handle quoted strings as a single token.
3.Iteration & Access
•Methods to check if more tokens exist: hasNext().
•Method to retrieve next token: next().
•Optional: method to reset the tokenizer to the start of the string.
🔐 Constraints & Assumptions
•Input string can be large; design for efficiency.
•Delimiters are configurable at runtime.
•Focus is on LLD and modularity, not regex-heavy parsing unless required.
🧱 Key Components & Classes
1.Tokenizer Class
1
2class StringTokenizer {
3private:
4 string input;
5 unordered_set<char> delimiters;
6 int currentPos;
7public:
8 StringTokenizer(string str, string delims);
9 bool hasNext();
10 string next();
11 void reset();
12};1.Optional: Token Class
•Represents a token and its metadata (start/end positions, original text).
1
2class Token {
3private:
4 string value;
5 int startIndex;
6 int endIndex;
7public:
8 string getValue();
9 int getStartIndex();
10 int getEndIndex();
11};🔄 Example Workflow
1.Initialize tokenizer:
1
2StringTokenizer tokenizer("apple,orange,,banana", ",");1.Iterate through tokens:
1
2while(tokenizer.hasNext()) {
3 string token = tokenizer.next();
4 // process token
5}1.Optional: reset tokenizer to start again.
🧪 Expected Deliverables
•Class diagram showing StringTokenizer and optional Token.
•Implementation of hasNext(), next(), and reset().
•Test cases:
•Standard delimiter splitting
•Multiple consecutive delimiters
•Custom delimiters
•Empty string and no delimiter edge cases
💡 Discussion Points
•Trade-offs between storing all tokens upfront vs generating tokens on-the-fly.
•Extensibility for quoted strings or regex-based tokenization.
•Memory efficiency for large input strings