|
| 1 | +StringTokenizer in Java |
| 2 | + |
| 3 | +## 1. Introduction |
| 4 | +- `StringTokenizer` is a legacy class in the `java.util` package. |
| 5 | +- It is used to **break a string into tokens** (smaller parts) based on **delimiters**. |
| 6 | +- Each token represents a meaningful unit extracted from the original string. |
| 7 | + |
| 8 | +--- |
| 9 | + |
| 10 | +## 2. How It Works |
| 11 | +- A `StringTokenizer` object takes: |
| 12 | + 1. The **input string**. |
| 13 | + 2. A **delimiter** (characters used to separate tokens, default is space `" "`). |
| 14 | +- It then sequentially scans the string and extracts tokens whenever it encounters a delimiter. |
| 15 | + |
| 16 | +--- |
| 17 | + |
| 18 | +## 3. Constructors |
| 19 | +1. `StringTokenizer(String str)` |
| 20 | + - Uses default delimiter (whitespace). |
| 21 | + |
| 22 | +2. `StringTokenizer(String str, String delim)` |
| 23 | + - Uses specified delimiter(s) (e.g., `","`, `";"`). |
| 24 | + |
| 25 | +3. `StringTokenizer(String str, String delim, boolean returnDelims)` |
| 26 | + - If `returnDelims` is true, delimiters themselves are returned as tokens. |
| 27 | + |
| 28 | +--- |
| 29 | + |
| 30 | +## 4. Common Methods |
| 31 | +- `boolean hasMoreTokens()` → checks if more tokens are available. |
| 32 | +- `String nextToken()` → returns the next token. |
| 33 | +- `int countTokens()` → returns the number of tokens left. |
| 34 | + |
| 35 | +--- |
| 36 | + |
| 37 | +## 5. Example (Conceptual) |
| 38 | +Given: |
| 39 | + |
| 40 | +“apple,banana,grape” |
| 41 | + |
| 42 | +Using `,` as delimiter → tokens are: |
| 43 | +- `"apple"` |
| 44 | +- `"banana"` |
| 45 | +- `"grape"` |
| 46 | + |
| 47 | +--- |
| 48 | + |
| 49 | +## 6. Limitations |
| 50 | +- **Legacy class**: Introduced in JDK 1.0; not recommended in modern code. |
| 51 | +- **No regex support**: Unlike `String.split()`, it cannot use regular expressions. |
| 52 | +- Less flexible than `Scanner` or `String.split()`. |
| 53 | + |
| 54 | +--- |
| 55 | + |
| 56 | +## 7. Use Cases |
| 57 | +- Simple tokenization where performance is critical and regex is not needed. |
| 58 | +- Parsing small config strings, command-line arguments, or CSV-like data. |
| 59 | + |
| 60 | +--- |
| 61 | + |
| 62 | +## 8. Key Takeaway |
| 63 | +- `StringTokenizer` is a **simple, fast tool** for breaking strings into tokens using delimiters. |
| 64 | +- For new projects, prefer `String.split()` or `Scanner` for more powerful parsing capabilities. |
| 65 | + |
| 66 | +⸻ |
0 commit comments