KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > cheatsheets > views > StringDelimitedTokenizer


1 /*******************************************************************************
2  * Copyright (c) 2002, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.ui.internal.cheatsheets.views;
12
13 public class StringDelimitedTokenizer {
14
15     private String JavaDoc str;
16     private String JavaDoc delimiter;
17     private int delimiterLength;
18     private int currentPosition;
19     private int maxPosition;
20
21     public StringDelimitedTokenizer(String JavaDoc str, String JavaDoc delim) {
22         currentPosition = 0;
23         this.str = str;
24         this.delimiter = delim;
25         maxPosition = this.str.length();
26         delimiterLength = this.delimiter.length();
27     }
28
29     public int countTokens() {
30         int count = 0;
31         int startPosition = 0;
32
33         while (startPosition < maxPosition && startPosition != -1) {
34             startPosition = str.indexOf(delimiter, startPosition);
35             if (startPosition != -1) {
36                 startPosition += delimiterLength;
37             }
38             count++;
39         }
40
41         return count;
42     }
43
44     public boolean endsWithDelimiter() {
45         return str.endsWith(delimiter);
46     }
47
48     public boolean hasMoreTokens() {
49         return (currentPosition < maxPosition);
50     }
51
52     public String JavaDoc nextToken() {
53         int position = str.indexOf(delimiter, currentPosition);
54         String JavaDoc token = null;
55         if (position == -1) {
56             token = str.substring(currentPosition);
57             currentPosition = maxPosition;
58         } else {
59             token = str.substring(currentPosition, position);
60             currentPosition = position + delimiterLength;
61         }
62         return token;
63     }
64 }
65
Popular Tags