001 /* This file is part of the project "Hilbert II" - http://www.qedeq.org
002 *
003 * Copyright 2000-2011, Michael Meyling <mime@qedeq.org>.
004 *
005 * "Hilbert II" is free software; you can redistribute
006 * it and/or modify it under the terms of the GNU General Public
007 * License as published by the Free Software Foundation; either
008 * version 2 of the License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013 * GNU General Public License for more details.
014 */
015
016 package org.qedeq.base.utility;
017
018 import java.util.Iterator;
019
020
021 /**
022 * Split given string into parts delimited by space.
023 *
024 * @author Michael Meyling
025 */
026 public final class Splitter implements Iterator {
027
028 /** Text to split. */
029 private final String text;
030
031 /** Separating delimiter. */
032 private final char delimiter;
033
034 /** Last found position. */
035 private int found;
036
037 /** Start searching from here. */
038 private int start;
039
040 /** Current found separator string. Consists of (perhaps several) delimiters. */
041 private String separator;
042
043 /** Current found token. */
044 private String token;
045
046 /**
047 * Constructor, should never be called.
048 *
049 * @param text Text to split.
050 */
051 public Splitter(final String text) {
052 this.text = text;
053 delimiter = ' ';
054 iterate();
055 }
056
057 /**
058 * Split String by given delimiter.
059 * "a b c" is converted to "a", " ", "b", " ", "c".
060 * "a b c " is converted to "a", " ", "b", " ", "c", " ".
061 *
062 * @return Split text.
063 */
064 public Object next() {
065 return nextToken();
066 }
067
068 /**
069 * Qualified next method.
070 *
071 * @return Get next token.
072 */
073 public String nextToken() {
074 if (token != null) {
075 final String result = token;
076 token = null;
077 return result;
078 }
079 if (separator != null) {
080 final String result = separator;
081 separator = null;
082 iterate();
083 return result;
084 }
085 return null;
086 }
087
088 /**
089 * Iterate token and whitespace.
090 */
091 private void iterate() {
092 found = text.indexOf(delimiter, start);
093 if (-1 < found) {
094 token = text.substring(start, found);
095 start = found;
096 while (found < text.length() && text.charAt(found) == ' ') {
097 found++;
098 }
099 separator = text.substring(start, found);
100 start = found;
101 if (found >= text.length()) {
102 found = -1;
103 }
104 } else {
105 separator = null;
106 token = text.substring(start);
107 }
108 if (token.length() == 0) {
109 token = null;
110 }
111 }
112
113 public boolean hasNext() {
114 return token != null || separator != null;
115 }
116
117
118 public void remove() {
119 throw new UnsupportedOperationException("this iterator doesn't support this method");
120 }
121
122 }
|