You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2021/01/17 15:42:28 UTC
[commons-text] branch master updated: Sort members.
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-text.git
The following commit(s) were added to refs/heads/master by this push:
new 3674e3d Sort members.
3674e3d is described below
commit 3674e3ddf6917891c6831064c63e2803bc95d62c
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Sun Jan 17 10:42:23 2021 -0500
Sort members.
---
.../java/org/apache/commons/text/StrBuilder.java | 3778 ++++++++++----------
.../java/org/apache/commons/text/StrTokenizer.java | 884 ++---
.../org/apache/commons/text/StringTokenizer.java | 842 ++---
3 files changed, 2752 insertions(+), 2752 deletions(-)
diff --git a/src/main/java/org/apache/commons/text/StrBuilder.java b/src/main/java/org/apache/commons/text/StrBuilder.java
index d11dbd2..ea92359 100644
--- a/src/main/java/org/apache/commons/text/StrBuilder.java
+++ b/src/main/java/org/apache/commons/text/StrBuilder.java
@@ -73,24 +73,202 @@ import org.apache.commons.lang3.StringUtils;
@Deprecated
public class StrBuilder implements CharSequence, Appendable, Serializable, Builder<String> {
+ //-----------------------------------------------------------------------
+ /**
+ * Inner class to allow StrBuilder to operate as a reader.
+ */
+ class StrBuilderReader extends Reader {
+ /** The current stream position. */
+ private int pos;
+ /** The last mark position. */
+ private int mark;
+
+ /**
+ * Default constructor.
+ */
+ StrBuilderReader() {
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void close() {
+ // do nothing
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void mark(final int readAheadLimit) {
+ mark = pos;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean markSupported() {
+ return true;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public int read() {
+ if (!ready()) {
+ return -1;
+ }
+ return StrBuilder.this.charAt(pos++);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public int read(final char[] b, final int off, int len) {
+ if (off < 0 || len < 0 || off > b.length
+ || off + len > b.length || off + len < 0) {
+ throw new IndexOutOfBoundsException();
+ }
+ if (len == 0) {
+ return 0;
+ }
+ if (pos >= StrBuilder.this.size()) {
+ return -1;
+ }
+ if (pos + len > size()) {
+ len = StrBuilder.this.size() - pos;
+ }
+ StrBuilder.this.getChars(pos, pos + len, b, off);
+ pos += len;
+ return len;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean ready() {
+ return pos < StrBuilder.this.size();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void reset() {
+ pos = mark;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public long skip(long n) {
+ if (pos + n > StrBuilder.this.size()) {
+ n = StrBuilder.this.size() - pos;
+ }
+ if (n < 0) {
+ return 0;
+ }
+ pos += n;
+ return n;
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Inner class to allow StrBuilder to operate as a tokenizer.
+ */
+ class StrBuilderTokenizer extends StrTokenizer {
+
+ /**
+ * Default constructor.
+ */
+ StrBuilderTokenizer() {
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String getContent() {
+ final String str = super.getContent();
+ if (str == null) {
+ return StrBuilder.this.toString();
+ }
+ return str;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected List<String> tokenize(final char[] chars, final int offset, final int count) {
+ if (chars == null) {
+ return super.tokenize(
+ StrBuilder.this.buffer, 0, StrBuilder.this.size());
+ }
+ return super.tokenize(chars, offset, count);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Inner class to allow StrBuilder to operate as a writer.
+ */
+ class StrBuilderWriter extends Writer {
+
+ /**
+ * Default constructor.
+ */
+ StrBuilderWriter() {
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void close() {
+ // do nothing
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void flush() {
+ // do nothing
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void write(final char[] cbuf) {
+ StrBuilder.this.append(cbuf);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void write(final char[] cbuf, final int off, final int len) {
+ StrBuilder.this.append(cbuf, off, len);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void write(final int c) {
+ StrBuilder.this.append((char) c);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void write(final String str) {
+ StrBuilder.this.append(str);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void write(final String str, final int off, final int len) {
+ StrBuilder.this.append(str, off, len);
+ }
+ }
/**
* The extra capacity for new builders.
*/
static final int CAPACITY = 32;
-
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 7628716375283629643L;
-
/** Internal data storage. */
char[] buffer; // package-protected for test code use only
+
/** Current size of the buffer. */
private int size;
+
/** The new line. */
private String newLine;
+
/** The null text. */
private String nullText;
@@ -129,443 +307,297 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
}
}
- //-----------------------------------------------------------------------
- /**
- * Gets the text to be appended when a new line is added.
- *
- * @return The new line text, null means use system default
- */
- public String getNewLineText() {
- return newLine;
- }
-
/**
- * Sets the text to be appended when a new line is added.
+ * Appends a boolean value to the string builder.
*
- * @param newLine the new line text, null means use system default
+ * @param value the value to append
* @return this, to enable chaining
*/
- public StrBuilder setNewLineText(final String newLine) {
- this.newLine = newLine;
+ public StrBuilder append(final boolean value) {
+ if (value) {
+ ensureCapacity(size + 4);
+ buffer[size++] = 't';
+ buffer[size++] = 'r';
+ buffer[size++] = 'u';
+ buffer[size++] = 'e';
+ } else {
+ ensureCapacity(size + 5);
+ buffer[size++] = 'f';
+ buffer[size++] = 'a';
+ buffer[size++] = 'l';
+ buffer[size++] = 's';
+ buffer[size++] = 'e';
+ }
return this;
}
- //-----------------------------------------------------------------------
/**
- * Gets the text to be appended when null is added.
+ * Appends a char value to the string builder.
*
- * @return The null text, null means no append
+ * @param ch the value to append
+ * @return this, to enable chaining
*/
- public String getNullText() {
- return nullText;
+ @Override
+ public StrBuilder append(final char ch) {
+ final int len = length();
+ ensureCapacity(len + 1);
+ buffer[size++] = ch;
+ return this;
}
/**
- * Sets the text to be appended when null is added.
+ * Appends a char array to the string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @param nullText the null text, null means no append
+ * @param chars the char array to append
* @return this, to enable chaining
*/
- public StrBuilder setNullText(String nullText) {
- if (nullText != null && nullText.isEmpty()) {
- nullText = null;
+ public StrBuilder append(final char[] chars) {
+ if (chars == null) {
+ return appendNull();
+ }
+ final int strLen = chars.length;
+ if (strLen > 0) {
+ final int len = length();
+ ensureCapacity(len + strLen);
+ System.arraycopy(chars, 0, buffer, len, strLen);
+ size += strLen;
}
- this.nullText = nullText;
return this;
}
- //-----------------------------------------------------------------------
/**
- * Gets the length of the string builder.
+ * Appends a char array to the string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @return The length
+ * @param chars the char array to append
+ * @param startIndex the start index, inclusive, must be valid
+ * @param length the length to append, must be valid
+ * @return this, to enable chaining
*/
- @Override
- public int length() {
- return size;
+ public StrBuilder append(final char[] chars, final int startIndex, final int length) {
+ if (chars == null) {
+ return appendNull();
+ }
+ if (startIndex < 0 || startIndex > chars.length) {
+ throw new StringIndexOutOfBoundsException("Invalid startIndex: " + length);
+ }
+ if (length < 0 || startIndex + length > chars.length) {
+ throw new StringIndexOutOfBoundsException("Invalid length: " + length);
+ }
+ if (length > 0) {
+ final int len = length();
+ ensureCapacity(len + length);
+ System.arraycopy(chars, startIndex, buffer, len, length);
+ size += length;
+ }
+ return this;
}
/**
- * Updates the length of the builder by either dropping the last characters
- * or adding filler of Unicode zero.
+ * Appends the contents of a char buffer to this string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @param length the length to set to, must be zero or positive
+ * @param buf the char buffer to append
* @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the length is negative
*/
- public StrBuilder setLength(final int length) {
- if (length < 0) {
- throw new StringIndexOutOfBoundsException(length);
+ public StrBuilder append(final CharBuffer buf) {
+ if (buf == null) {
+ return appendNull();
}
- if (length < size) {
- size = length;
- } else if (length > size) {
- ensureCapacity(length);
- final int oldEnd = size;
- final int newEnd = length;
- size = length;
- for (int i = oldEnd; i < newEnd; i++) {
- buffer[i] = '\0';
- }
+ if (buf.hasArray()) {
+ final int length = buf.remaining();
+ final int len = length();
+ ensureCapacity(len + length);
+ System.arraycopy(buf.array(), buf.arrayOffset() + buf.position(), buffer, len, length);
+ size += length;
+ } else {
+ append(buf.toString());
}
return this;
}
- //-----------------------------------------------------------------------
/**
- * Gets the current size of the internal character array buffer.
+ * Appends the contents of a char buffer to this string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @return The capacity
+ * @param buf the char buffer to append
+ * @param startIndex the start index, inclusive, must be valid
+ * @param length the length to append, must be valid
+ * @return this, to enable chaining
*/
- public int capacity() {
- return buffer.length;
+ public StrBuilder append(final CharBuffer buf, final int startIndex, final int length) {
+ if (buf == null) {
+ return appendNull();
+ }
+ if (buf.hasArray()) {
+ final int totalLength = buf.remaining();
+ if (startIndex < 0 || startIndex > totalLength) {
+ throw new StringIndexOutOfBoundsException("startIndex must be valid");
+ }
+ if (length < 0 || startIndex + length > totalLength) {
+ throw new StringIndexOutOfBoundsException("length must be valid");
+ }
+ final int len = length();
+ ensureCapacity(len + length);
+ System.arraycopy(buf.array(), buf.arrayOffset() + buf.position() + startIndex, buffer, len, length);
+ size += length;
+ } else {
+ append(buf.toString(), startIndex, length);
+ }
+ return this;
}
/**
- * Checks the capacity and ensures that it is at least the size specified.
+ * Appends a CharSequence to this string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @param capacity the capacity to ensure
+ * @param seq the CharSequence to append
* @return this, to enable chaining
*/
- public StrBuilder ensureCapacity(final int capacity) {
- if (capacity > buffer.length) {
- final char[] old = buffer;
- buffer = new char[capacity * 2];
- System.arraycopy(old, 0, buffer, 0, size);
+ @Override
+ public StrBuilder append(final CharSequence seq) {
+ if (seq == null) {
+ return appendNull();
}
- return this;
+ if (seq instanceof StrBuilder) {
+ return append((StrBuilder) seq);
+ }
+ if (seq instanceof StringBuilder) {
+ return append((StringBuilder) seq);
+ }
+ if (seq instanceof StringBuffer) {
+ return append((StringBuffer) seq);
+ }
+ if (seq instanceof CharBuffer) {
+ return append((CharBuffer) seq);
+ }
+ return append(seq.toString());
}
/**
- * Minimizes the capacity to the actual length of the string.
+ * Appends part of a CharSequence to this string builder.
+ * Appending null will call {@link #appendNull()}.
*
+ * @param seq the CharSequence to append
+ * @param startIndex the start index, inclusive, must be valid
+ * @param length the length to append, must be valid
* @return this, to enable chaining
*/
- public StrBuilder minimizeCapacity() {
- if (buffer.length > length()) {
- final char[] old = buffer;
- buffer = new char[length()];
- System.arraycopy(old, 0, buffer, 0, size);
+ @Override
+ public StrBuilder append(final CharSequence seq, final int startIndex, final int length) {
+ if (seq == null) {
+ return appendNull();
}
- return this;
+ return append(seq.toString(), startIndex, length);
}
- //-----------------------------------------------------------------------
/**
- * Gets the length of the string builder.
- * <p>
- * This method is the same as {@link #length()} and is provided to match the
- * API of Collections.
+ * Appends a double value to the string builder using {@code String.valueOf}.
*
- * @return The length
+ * @param value the value to append
+ * @return this, to enable chaining
*/
- public int size() {
- return size;
+ public StrBuilder append(final double value) {
+ return append(String.valueOf(value));
}
/**
- * Checks is the string builder is empty (convenience Collections API style method).
- * <p>
- * This method is the same as checking {@link #length()} and is provided to match the
- * API of Collections.
+ * Appends a float value to the string builder using {@code String.valueOf}.
*
- * @return {@code true} if the size is {@code 0}.
+ * @param value the value to append
+ * @return this, to enable chaining
*/
- public boolean isEmpty() {
- return size == 0;
+ public StrBuilder append(final float value) {
+ return append(String.valueOf(value));
}
/**
- * Checks is the string builder is not empty (convenience Collections API style method).
- * <p>
- * This method is the same as checking {@link #length()} and is provided to match the
- * API of Collections.
+ * Appends an int value to the string builder using {@code String.valueOf}.
*
- * @return {@code true} if the size is greater than {@code 0}.
- * @since 1.10.0
+ * @param value the value to append
+ * @return this, to enable chaining
*/
- public boolean isNotEmpty() {
- return size > 0;
+ public StrBuilder append(final int value) {
+ return append(String.valueOf(value));
}
/**
- * Clears the string builder (convenience Collections API style method).
- * <p>
- * This method does not reduce the size of the internal character buffer.
- * To do that, call {@code clear()} followed by {@link #minimizeCapacity()}.
- * <p>
- * This method is the same as {@link #setLength(int)} called with zero
- * and is provided to match the API of Collections.
+ * Appends a long value to the string builder using {@code String.valueOf}.
*
+ * @param value the value to append
* @return this, to enable chaining
*/
- public StrBuilder clear() {
- size = 0;
- return this;
+ public StrBuilder append(final long value) {
+ return append(String.valueOf(value));
}
- //-----------------------------------------------------------------------
/**
- * Gets the character at the specified index.
+ * Appends an object to this string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @see #setCharAt(int, char)
- * @see #deleteCharAt(int)
- * @param index the index to retrieve, must be valid
- * @return The character at the index
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param obj the object to append
+ * @return this, to enable chaining
*/
- @Override
- public char charAt(final int index) {
- if (index < 0 || index >= length()) {
- throw new StringIndexOutOfBoundsException(index);
+ public StrBuilder append(final Object obj) {
+ if (obj == null) {
+ return appendNull();
}
- return buffer[index];
+ if (obj instanceof CharSequence) {
+ return append((CharSequence) obj);
+ }
+ return append(obj.toString());
}
/**
- * Sets the character at the specified index.
+ * Appends another string builder to this string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @see #charAt(int)
- * @see #deleteCharAt(int)
- * @param index the index to set
- * @param ch the new character
+ * @param str the string builder to append
* @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder setCharAt(final int index, final char ch) {
- if (index < 0 || index >= length()) {
- throw new StringIndexOutOfBoundsException(index);
+ public StrBuilder append(final StrBuilder str) {
+ if (str == null) {
+ return appendNull();
+ }
+ final int strLen = str.length();
+ if (strLen > 0) {
+ final int len = length();
+ ensureCapacity(len + strLen);
+ System.arraycopy(str.buffer, 0, buffer, len, strLen);
+ size += strLen;
}
- buffer[index] = ch;
return this;
}
/**
- * Deletes the character at the specified index.
+ * Appends part of a string builder to this string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @see #charAt(int)
- * @see #setCharAt(int, char)
- * @param index the index to delete
+ * @param str the string to append
+ * @param startIndex the start index, inclusive, must be valid
+ * @param length the length to append, must be valid
* @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder deleteCharAt(final int index) {
- if (index < 0 || index >= size) {
- throw new StringIndexOutOfBoundsException(index);
+ public StrBuilder append(final StrBuilder str, final int startIndex, final int length) {
+ if (str == null) {
+ return appendNull();
+ }
+ if (startIndex < 0 || startIndex > str.length()) {
+ throw new StringIndexOutOfBoundsException("startIndex must be valid");
+ }
+ if (length < 0 || startIndex + length > str.length()) {
+ throw new StringIndexOutOfBoundsException("length must be valid");
+ }
+ if (length > 0) {
+ final int len = length();
+ ensureCapacity(len + length);
+ str.getChars(startIndex, startIndex + length, buffer, len);
+ size += length;
}
- deleteImpl(index, index + 1, 1);
return this;
}
- //-----------------------------------------------------------------------
- /**
- * Copies the builder's character array into a new character array.
- *
- * @return a new array that represents the contents of the builder
- */
- public char[] toCharArray() {
- if (size == 0) {
- return ArrayUtils.EMPTY_CHAR_ARRAY;
- }
- final char[] chars = new char[size];
- System.arraycopy(buffer, 0, chars, 0, size);
- return chars;
- }
-
- /**
- * Copies part of the builder's character array into a new character array.
- *
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except that
- * if too large it is treated as end of string
- * @return a new array that holds part of the contents of the builder
- * @throws IndexOutOfBoundsException if startIndex is invalid,
- * or if endIndex is invalid (but endIndex greater than size is valid)
- */
- public char[] toCharArray(final int startIndex, int endIndex) {
- endIndex = validateRange(startIndex, endIndex);
- final int len = endIndex - startIndex;
- if (len == 0) {
- return ArrayUtils.EMPTY_CHAR_ARRAY;
- }
- final char[] chars = new char[len];
- System.arraycopy(buffer, startIndex, chars, 0, len);
- return chars;
- }
-
- /**
- * Copies the character array into the specified array.
- *
- * @param destination the destination array, null will cause an array to be created
- * @return The input array, unless that was null or too small
- */
- public char[] getChars(char[] destination) {
- final int len = length();
- if (destination == null || destination.length < len) {
- destination = new char[len];
- }
- System.arraycopy(buffer, 0, destination, 0, len);
- return destination;
- }
-
- /**
- * Copies the character array into the specified array.
- *
- * @param startIndex first index to copy, inclusive, must be valid
- * @param endIndex last index, exclusive, must be valid
- * @param destination the destination array, must not be null or too small
- * @param destinationIndex the index to start copying in destination
- * @throws NullPointerException if the array is null
- * @throws IndexOutOfBoundsException if any index is invalid
- */
- public void getChars(final int startIndex,
- final int endIndex,
- final char[] destination,
- final int destinationIndex) {
- if (startIndex < 0) {
- throw new StringIndexOutOfBoundsException(startIndex);
- }
- if (endIndex < 0 || endIndex > length()) {
- throw new StringIndexOutOfBoundsException(endIndex);
- }
- if (startIndex > endIndex) {
- throw new StringIndexOutOfBoundsException("end < start");
- }
- System.arraycopy(buffer, startIndex, destination, destinationIndex, endIndex - startIndex);
- }
-
- //-----------------------------------------------------------------------
- /**
- * If possible, reads chars from the provided {@link Readable} directly into underlying
- * character buffer without making extra copies.
- *
- * @param readable object to read from
- * @return The number of characters read
- * @throws IOException if an I/O error occurs
- *
- * @see #appendTo(Appendable)
- */
- public int readFrom(final Readable readable) throws IOException {
- final int oldSize = size;
- if (readable instanceof Reader) {
- final Reader r = (Reader) readable;
- ensureCapacity(size + 1);
- int read;
- while ((read = r.read(buffer, size, buffer.length - size)) != -1) {
- size += read;
- ensureCapacity(size + 1);
- }
- } else if (readable instanceof CharBuffer) {
- final CharBuffer cb = (CharBuffer) readable;
- final int remaining = cb.remaining();
- ensureCapacity(size + remaining);
- cb.get(buffer, size, remaining);
- size += remaining;
- } else {
- while (true) {
- ensureCapacity(size + 1);
- final CharBuffer buf = CharBuffer.wrap(buffer, size, buffer.length - size);
- final int read = readable.read(buf);
- if (read == -1) {
- break;
- }
- size += read;
- }
- }
- return size - oldSize;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Appends the new line string to this string builder.
- * <p>
- * The new line string can be altered using {@link #setNewLineText(String)}.
- * This might be used to force the output to always use Unix line endings
- * even when on Windows.
- *
- * @return this, to enable chaining
- */
- public StrBuilder appendNewLine() {
- if (newLine == null) {
- append(System.lineSeparator());
- return this;
- }
- return append(newLine);
- }
-
- /**
- * Appends the text representing {@code null} to this string builder.
- *
- * @return this, to enable chaining
- */
- public StrBuilder appendNull() {
- if (nullText == null) {
- return this;
- }
- return append(nullText);
- }
-
- /**
- * Appends an object to this string builder.
- * Appending null will call {@link #appendNull()}.
- *
- * @param obj the object to append
- * @return this, to enable chaining
- */
- public StrBuilder append(final Object obj) {
- if (obj == null) {
- return appendNull();
- }
- if (obj instanceof CharSequence) {
- return append((CharSequence) obj);
- }
- return append(obj.toString());
- }
-
- /**
- * Appends a CharSequence to this string builder.
- * Appending null will call {@link #appendNull()}.
- *
- * @param seq the CharSequence to append
- * @return this, to enable chaining
- */
- @Override
- public StrBuilder append(final CharSequence seq) {
- if (seq == null) {
- return appendNull();
- }
- if (seq instanceof StrBuilder) {
- return append((StrBuilder) seq);
- }
- if (seq instanceof StringBuilder) {
- return append((StringBuilder) seq);
- }
- if (seq instanceof StringBuffer) {
- return append((StringBuffer) seq);
- }
- if (seq instanceof CharBuffer) {
- return append((CharBuffer) seq);
- }
- return append(seq.toString());
- }
-
- /**
- * Appends part of a CharSequence to this string builder.
- * Appending null will call {@link #appendNull()}.
- *
- * @param seq the CharSequence to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
- */
- @Override
- public StrBuilder append(final CharSequence seq, final int startIndex, final int length) {
- if (seq == null) {
- return appendNull();
- }
- return append(seq.toString(), startIndex, length);
- }
-
/**
* Appends a string to this string builder.
* Appending null will call {@link #appendNull()}.
@@ -587,7 +619,6 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
return this;
}
-
/**
* Appends part of a string to this string builder.
* Appending null will call {@link #appendNull()}.
@@ -629,110 +660,56 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
}
/**
- * Appends the contents of a char buffer to this string builder.
+ * Appends a string buffer to this string builder.
* Appending null will call {@link #appendNull()}.
*
- * @param buf the char buffer to append
+ * @param str the string buffer to append
* @return this, to enable chaining
*/
- public StrBuilder append(final CharBuffer buf) {
- if (buf == null) {
+ public StrBuilder append(final StringBuffer str) {
+ if (str == null) {
return appendNull();
}
- if (buf.hasArray()) {
- final int length = buf.remaining();
+ final int strLen = str.length();
+ if (strLen > 0) {
final int len = length();
- ensureCapacity(len + length);
- System.arraycopy(buf.array(), buf.arrayOffset() + buf.position(), buffer, len, length);
- size += length;
- } else {
- append(buf.toString());
+ ensureCapacity(len + strLen);
+ str.getChars(0, strLen, buffer, len);
+ size += strLen;
}
return this;
}
/**
- * Appends the contents of a char buffer to this string builder.
+ * Appends part of a string buffer to this string builder.
* Appending null will call {@link #appendNull()}.
*
- * @param buf the char buffer to append
+ * @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
- public StrBuilder append(final CharBuffer buf, final int startIndex, final int length) {
- if (buf == null) {
+ public StrBuilder append(final StringBuffer str, final int startIndex, final int length) {
+ if (str == null) {
return appendNull();
}
- if (buf.hasArray()) {
- final int totalLength = buf.remaining();
- if (startIndex < 0 || startIndex > totalLength) {
- throw new StringIndexOutOfBoundsException("startIndex must be valid");
- }
- if (length < 0 || startIndex + length > totalLength) {
- throw new StringIndexOutOfBoundsException("length must be valid");
- }
+ if (startIndex < 0 || startIndex > str.length()) {
+ throw new StringIndexOutOfBoundsException("startIndex must be valid");
+ }
+ if (length < 0 || startIndex + length > str.length()) {
+ throw new StringIndexOutOfBoundsException("length must be valid");
+ }
+ if (length > 0) {
final int len = length();
ensureCapacity(len + length);
- System.arraycopy(buf.array(), buf.arrayOffset() + buf.position() + startIndex, buffer, len, length);
+ str.getChars(startIndex, startIndex + length, buffer, len);
size += length;
- } else {
- append(buf.toString(), startIndex, length);
}
return this;
}
/**
- * Appends a string buffer to this string builder.
- * Appending null will call {@link #appendNull()}.
- *
- * @param str the string buffer to append
- * @return this, to enable chaining
- */
- public StrBuilder append(final StringBuffer str) {
- if (str == null) {
- return appendNull();
- }
- final int strLen = str.length();
- if (strLen > 0) {
- final int len = length();
- ensureCapacity(len + strLen);
- str.getChars(0, strLen, buffer, len);
- size += strLen;
- }
- return this;
- }
-
- /**
- * Appends part of a string buffer to this string builder.
- * Appending null will call {@link #appendNull()}.
- *
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
- * @return this, to enable chaining
- */
- public StrBuilder append(final StringBuffer str, final int startIndex, final int length) {
- if (str == null) {
- return appendNull();
- }
- if (startIndex < 0 || startIndex > str.length()) {
- throw new StringIndexOutOfBoundsException("startIndex must be valid");
- }
- if (length < 0 || startIndex + length > str.length()) {
- throw new StringIndexOutOfBoundsException("length must be valid");
- }
- if (length > 0) {
- final int len = length();
- ensureCapacity(len + length);
- str.getChars(startIndex, startIndex + length, buffer, len);
- size += length;
- }
- return this;
- }
-
- /**
- * Appends a StringBuilder to this string builder.
+ * Appends a StringBuilder to this string builder.
* Appending null will call {@link #appendNull()}.
*
* @param str the StringBuilder to append
@@ -781,275 +758,254 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
}
/**
- * Appends another string builder to this string builder.
- * Appending null will call {@link #appendNull()}.
+ * Appends each item in an iterable to the builder without any separators.
+ * Appending a null iterable will have no effect.
+ * Each object is appended using {@link #append(Object)}.
*
- * @param str the string builder to append
+ * @param iterable the iterable to append
* @return this, to enable chaining
*/
- public StrBuilder append(final StrBuilder str) {
- if (str == null) {
- return appendNull();
- }
- final int strLen = str.length();
- if (strLen > 0) {
- final int len = length();
- ensureCapacity(len + strLen);
- System.arraycopy(str.buffer, 0, buffer, len, strLen);
- size += strLen;
+ public StrBuilder appendAll(final Iterable<?> iterable) {
+ if (iterable != null) {
+ for (final Object o : iterable) {
+ append(o);
+ }
}
return this;
}
/**
- * Appends part of a string builder to this string builder.
- * Appending null will call {@link #appendNull()}.
+ * Appends each item in an iterator to the builder without any separators.
+ * Appending a null iterator will have no effect.
+ * Each object is appended using {@link #append(Object)}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param it the iterator to append
* @return this, to enable chaining
*/
- public StrBuilder append(final StrBuilder str, final int startIndex, final int length) {
- if (str == null) {
- return appendNull();
- }
- if (startIndex < 0 || startIndex > str.length()) {
- throw new StringIndexOutOfBoundsException("startIndex must be valid");
- }
- if (length < 0 || startIndex + length > str.length()) {
- throw new StringIndexOutOfBoundsException("length must be valid");
- }
- if (length > 0) {
- final int len = length();
- ensureCapacity(len + length);
- str.getChars(startIndex, startIndex + length, buffer, len);
- size += length;
+ public StrBuilder appendAll(final Iterator<?> it) {
+ if (it != null) {
+ while (it.hasNext()) {
+ append(it.next());
+ }
}
return this;
}
+
+ //-----------------------------------------------------------------------
/**
- * Appends a char array to the string builder.
- * Appending null will call {@link #appendNull()}.
+ * Appends each item in an array to the builder without any separators.
+ * Appending a null array will have no effect.
+ * Each object is appended using {@link #append(Object)}.
*
- * @param chars the char array to append
+ * @param <T> the element type
+ * @param array the array to append
* @return this, to enable chaining
*/
- public StrBuilder append(final char[] chars) {
- if (chars == null) {
- return appendNull();
- }
- final int strLen = chars.length;
- if (strLen > 0) {
- final int len = length();
- ensureCapacity(len + strLen);
- System.arraycopy(chars, 0, buffer, len, strLen);
- size += strLen;
+ public <T> StrBuilder appendAll(@SuppressWarnings("unchecked") final T... array) {
+ /*
+ * @SuppressWarnings used to hide warning about vararg usage. We cannot
+ * use @SafeVarargs, since this method is not final. Using @SuppressWarnings
+ * is fine, because it isn't inherited by subclasses, so each subclass must
+ * vouch for itself whether its use of 'array' is safe.
+ */
+ if (array != null && array.length > 0) {
+ for (final Object element : array) {
+ append(element);
+ }
}
return this;
}
/**
- * Appends a char array to the string builder.
- * Appending null will call {@link #appendNull()}.
+ * Appends an object to the builder padding on the left to a fixed width.
+ * The {@code String.valueOf} of the {@code int} value is used.
+ * If the formatted value is larger than the length, the left hand side is lost.
*
- * @param chars the char array to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param value the value to append
+ * @param width the fixed field width, zero or negative has no effect
+ * @param padChar the pad character to use
* @return this, to enable chaining
*/
- public StrBuilder append(final char[] chars, final int startIndex, final int length) {
- if (chars == null) {
- return appendNull();
- }
- if (startIndex < 0 || startIndex > chars.length) {
- throw new StringIndexOutOfBoundsException("Invalid startIndex: " + length);
- }
- if (length < 0 || startIndex + length > chars.length) {
- throw new StringIndexOutOfBoundsException("Invalid length: " + length);
- }
- if (length > 0) {
- final int len = length();
- ensureCapacity(len + length);
- System.arraycopy(chars, startIndex, buffer, len, length);
- size += length;
- }
- return this;
+ public StrBuilder appendFixedWidthPadLeft(final int value, final int width, final char padChar) {
+ return appendFixedWidthPadLeft(String.valueOf(value), width, padChar);
}
+ //-----------------------------------------------------------------------
/**
- * Appends a boolean value to the string builder.
+ * Appends an object to the builder padding on the left to a fixed width.
+ * The {@code toString} of the object is used.
+ * If the object is larger than the length, the left hand side is lost.
+ * If the object is null, the null text value is used.
*
- * @param value the value to append
+ * @param obj the object to append, null uses null text
+ * @param width the fixed field width, zero or negative has no effect
+ * @param padChar the pad character to use
* @return this, to enable chaining
*/
- public StrBuilder append(final boolean value) {
- if (value) {
- ensureCapacity(size + 4);
- buffer[size++] = 't';
- buffer[size++] = 'r';
- buffer[size++] = 'u';
- buffer[size++] = 'e';
- } else {
- ensureCapacity(size + 5);
- buffer[size++] = 'f';
- buffer[size++] = 'a';
- buffer[size++] = 'l';
- buffer[size++] = 's';
- buffer[size++] = 'e';
+ public StrBuilder appendFixedWidthPadLeft(final Object obj, final int width, final char padChar) {
+ if (width > 0) {
+ ensureCapacity(size + width);
+ String str = obj == null ? getNullText() : obj.toString();
+ if (str == null) {
+ str = StringUtils.EMPTY;
+ }
+ final int strLen = str.length();
+ if (strLen >= width) {
+ str.getChars(strLen - width, strLen, buffer, size);
+ } else {
+ final int padLen = width - strLen;
+ for (int i = 0; i < padLen; i++) {
+ buffer[size + i] = padChar;
+ }
+ str.getChars(0, strLen, buffer, size + padLen);
+ }
+ size += width;
}
return this;
}
/**
- * Appends a char value to the string builder.
+ * Appends an object to the builder padding on the right to a fixed length.
+ * The {@code String.valueOf} of the {@code int} value is used.
+ * If the object is larger than the length, the right hand side is lost.
*
- * @param ch the value to append
+ * @param value the value to append
+ * @param width the fixed field width, zero or negative has no effect
+ * @param padChar the pad character to use
* @return this, to enable chaining
*/
- @Override
- public StrBuilder append(final char ch) {
- final int len = length();
- ensureCapacity(len + 1);
- buffer[size++] = ch;
- return this;
+ public StrBuilder appendFixedWidthPadRight(final int value, final int width, final char padChar) {
+ return appendFixedWidthPadRight(String.valueOf(value), width, padChar);
}
/**
- * Appends an int value to the string builder using {@code String.valueOf}.
+ * Appends an object to the builder padding on the right to a fixed length.
+ * The {@code toString} of the object is used.
+ * If the object is larger than the length, the right hand side is lost.
+ * If the object is null, null text value is used.
*
- * @param value the value to append
+ * @param obj the object to append, null uses null text
+ * @param width the fixed field width, zero or negative has no effect
+ * @param padChar the pad character to use
* @return this, to enable chaining
*/
- public StrBuilder append(final int value) {
- return append(String.valueOf(value));
+ public StrBuilder appendFixedWidthPadRight(final Object obj, final int width, final char padChar) {
+ if (width > 0) {
+ ensureCapacity(size + width);
+ String str = obj == null ? getNullText() : obj.toString();
+ if (str == null) {
+ str = StringUtils.EMPTY;
+ }
+ final int strLen = str.length();
+ if (strLen >= width) {
+ str.getChars(0, width, buffer, size);
+ } else {
+ final int padLen = width - strLen;
+ str.getChars(0, strLen, buffer, size);
+ for (int i = 0; i < padLen; i++) {
+ buffer[size + strLen + i] = padChar;
+ }
+ }
+ size += width;
+ }
+ return this;
}
/**
- * Appends a long value to the string builder using {@code String.valueOf}.
+ * Appends a boolean value followed by a new line to the string builder.
*
* @param value the value to append
* @return this, to enable chaining
*/
- public StrBuilder append(final long value) {
- return append(String.valueOf(value));
+ public StrBuilder appendln(final boolean value) {
+ return append(value).appendNewLine();
}
/**
- * Appends a float value to the string builder using {@code String.valueOf}.
- *
- * @param value the value to append
- * @return this, to enable chaining
- */
- public StrBuilder append(final float value) {
- return append(String.valueOf(value));
- }
-
- /**
- * Appends a double value to the string builder using {@code String.valueOf}.
- *
- * @param value the value to append
- * @return this, to enable chaining
- */
- public StrBuilder append(final double value) {
- return append(String.valueOf(value));
- }
-
- //-----------------------------------------------------------------------
- /**
- * Appends an object followed by a new line to this string builder.
- * Appending null will call {@link #appendNull()}.
+ * Appends a char value followed by a new line to the string builder.
*
- * @param obj the object to append
+ * @param ch the value to append
* @return this, to enable chaining
*/
- public StrBuilder appendln(final Object obj) {
- return append(obj).appendNewLine();
+ public StrBuilder appendln(final char ch) {
+ return append(ch).appendNewLine();
}
/**
- * Appends a string followed by a new line to this string builder.
+ * Appends a char array followed by a new line to the string builder.
* Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
+ * @param chars the char array to append
* @return this, to enable chaining
*/
- public StrBuilder appendln(final String str) {
- return append(str).appendNewLine();
+ public StrBuilder appendln(final char[] chars) {
+ return append(chars).appendNewLine();
}
/**
- * Appends part of a string followed by a new line to this string builder.
+ * Appends a char array followed by a new line to the string builder.
* Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
+ * @param chars the char array to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
- public StrBuilder appendln(final String str, final int startIndex, final int length) {
- return append(str, startIndex, length).appendNewLine();
+ public StrBuilder appendln(final char[] chars, final int startIndex, final int length) {
+ return append(chars, startIndex, length).appendNewLine();
}
/**
- * Calls {@link String#format(String, Object...)} and appends the result.
+ * Appends a double value followed by a new line to the string builder using {@code String.valueOf}.
*
- * @param format the format string
- * @param objs the objects to use in the format string
- * @return {@code this} to enable chaining
- * @see String#format(String, Object...)
+ * @param value the value to append
+ * @return this, to enable chaining
*/
- public StrBuilder appendln(final String format, final Object... objs) {
- return append(format, objs).appendNewLine();
+ public StrBuilder appendln(final double value) {
+ return append(value).appendNewLine();
}
/**
- * Appends a string buffer followed by a new line to this string builder.
- * Appending null will call {@link #appendNull()}.
+ * Appends a float value followed by a new line to the string builder using {@code String.valueOf}.
*
- * @param str the string buffer to append
+ * @param value the value to append
* @return this, to enable chaining
*/
- public StrBuilder appendln(final StringBuffer str) {
- return append(str).appendNewLine();
+ public StrBuilder appendln(final float value) {
+ return append(value).appendNewLine();
}
/**
- * Appends a string builder followed by a new line to this string builder.
- * Appending null will call {@link #appendNull()}.
+ * Appends an int value followed by a new line to the string builder using {@code String.valueOf}.
*
- * @param str the string builder to append
+ * @param value the value to append
* @return this, to enable chaining
*/
- public StrBuilder appendln(final StringBuilder str) {
- return append(str).appendNewLine();
+ public StrBuilder appendln(final int value) {
+ return append(value).appendNewLine();
}
/**
- * Appends part of a string builder followed by a new line to this string builder.
- * Appending null will call {@link #appendNull()}.
+ * Appends a long value followed by a new line to the string builder using {@code String.valueOf}.
*
- * @param str the string builder to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param value the value to append
* @return this, to enable chaining
*/
- public StrBuilder appendln(final StringBuilder str, final int startIndex, final int length) {
- return append(str, startIndex, length).appendNewLine();
+ public StrBuilder appendln(final long value) {
+ return append(value).appendNewLine();
}
+ //-----------------------------------------------------------------------
/**
- * Appends part of a string buffer followed by a new line to this string builder.
+ * Appends an object followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
- * @param str the string to append
- * @param startIndex the start index, inclusive, must be valid
- * @param length the length to append, must be valid
+ * @param obj the object to append
* @return this, to enable chaining
*/
- public StrBuilder appendln(final StringBuffer str, final int startIndex, final int length) {
- return append(str, startIndex, length).appendNewLine();
+ public StrBuilder appendln(final Object obj) {
+ return append(obj).appendNewLine();
}
/**
@@ -1077,214 +1033,204 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
}
/**
- * Appends a char array followed by a new line to the string builder.
+ * Appends a string followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
- * @param chars the char array to append
+ * @param str the string to append
* @return this, to enable chaining
*/
- public StrBuilder appendln(final char[] chars) {
- return append(chars).appendNewLine();
+ public StrBuilder appendln(final String str) {
+ return append(str).appendNewLine();
}
/**
- * Appends a char array followed by a new line to the string builder.
+ * Appends part of a string followed by a new line to this string builder.
* Appending null will call {@link #appendNull()}.
*
- * @param chars the char array to append
+ * @param str the string to append
* @param startIndex the start index, inclusive, must be valid
* @param length the length to append, must be valid
* @return this, to enable chaining
*/
- public StrBuilder appendln(final char[] chars, final int startIndex, final int length) {
- return append(chars, startIndex, length).appendNewLine();
+ public StrBuilder appendln(final String str, final int startIndex, final int length) {
+ return append(str, startIndex, length).appendNewLine();
}
/**
- * Appends a boolean value followed by a new line to the string builder.
+ * Calls {@link String#format(String, Object...)} and appends the result.
*
- * @param value the value to append
- * @return this, to enable chaining
+ * @param format the format string
+ * @param objs the objects to use in the format string
+ * @return {@code this} to enable chaining
+ * @see String#format(String, Object...)
*/
- public StrBuilder appendln(final boolean value) {
- return append(value).appendNewLine();
+ public StrBuilder appendln(final String format, final Object... objs) {
+ return append(format, objs).appendNewLine();
}
/**
- * Appends a char value followed by a new line to the string builder.
+ * Appends a string buffer followed by a new line to this string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @param ch the value to append
+ * @param str the string buffer to append
* @return this, to enable chaining
*/
- public StrBuilder appendln(final char ch) {
- return append(ch).appendNewLine();
+ public StrBuilder appendln(final StringBuffer str) {
+ return append(str).appendNewLine();
}
/**
- * Appends an int value followed by a new line to the string builder using {@code String.valueOf}.
+ * Appends part of a string buffer followed by a new line to this string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @param value the value to append
+ * @param str the string to append
+ * @param startIndex the start index, inclusive, must be valid
+ * @param length the length to append, must be valid
* @return this, to enable chaining
*/
- public StrBuilder appendln(final int value) {
- return append(value).appendNewLine();
+ public StrBuilder appendln(final StringBuffer str, final int startIndex, final int length) {
+ return append(str, startIndex, length).appendNewLine();
}
/**
- * Appends a long value followed by a new line to the string builder using {@code String.valueOf}.
+ * Appends a string builder followed by a new line to this string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @param value the value to append
+ * @param str the string builder to append
* @return this, to enable chaining
*/
- public StrBuilder appendln(final long value) {
- return append(value).appendNewLine();
+ public StrBuilder appendln(final StringBuilder str) {
+ return append(str).appendNewLine();
}
/**
- * Appends a float value followed by a new line to the string builder using {@code String.valueOf}.
+ * Appends part of a string builder followed by a new line to this string builder.
+ * Appending null will call {@link #appendNull()}.
*
- * @param value the value to append
+ * @param str the string builder to append
+ * @param startIndex the start index, inclusive, must be valid
+ * @param length the length to append, must be valid
* @return this, to enable chaining
*/
- public StrBuilder appendln(final float value) {
- return append(value).appendNewLine();
+ public StrBuilder appendln(final StringBuilder str, final int startIndex, final int length) {
+ return append(str, startIndex, length).appendNewLine();
}
+ //-----------------------------------------------------------------------
/**
- * Appends a double value followed by a new line to the string builder using {@code String.valueOf}.
+ * Appends the new line string to this string builder.
+ * <p>
+ * The new line string can be altered using {@link #setNewLineText(String)}.
+ * This might be used to force the output to always use Unix line endings
+ * even when on Windows.
*
- * @param value the value to append
* @return this, to enable chaining
*/
- public StrBuilder appendln(final double value) {
- return append(value).appendNewLine();
+ public StrBuilder appendNewLine() {
+ if (newLine == null) {
+ append(System.lineSeparator());
+ return this;
+ }
+ return append(newLine);
}
- //-----------------------------------------------------------------------
/**
- * Appends each item in an array to the builder without any separators.
- * Appending a null array will have no effect.
- * Each object is appended using {@link #append(Object)}.
+ * Appends the text representing {@code null} to this string builder.
*
- * @param <T> the element type
- * @param array the array to append
* @return this, to enable chaining
*/
- public <T> StrBuilder appendAll(@SuppressWarnings("unchecked") final T... array) {
- /*
- * @SuppressWarnings used to hide warning about vararg usage. We cannot
- * use @SafeVarargs, since this method is not final. Using @SuppressWarnings
- * is fine, because it isn't inherited by subclasses, so each subclass must
- * vouch for itself whether its use of 'array' is safe.
- */
- if (array != null && array.length > 0) {
- for (final Object element : array) {
- append(element);
- }
+ public StrBuilder appendNull() {
+ if (nullText == null) {
+ return this;
}
- return this;
+ return append(nullText);
}
+ //-----------------------------------------------------------------------
/**
- * Appends each item in an iterable to the builder without any separators.
- * Appending a null iterable will have no effect.
- * Each object is appended using {@link #append(Object)}.
+ * Appends the pad character to the builder the specified number of times.
*
- * @param iterable the iterable to append
+ * @param length the length to append, negative means no append
+ * @param padChar the character to append
* @return this, to enable chaining
*/
- public StrBuilder appendAll(final Iterable<?> iterable) {
- if (iterable != null) {
- for (final Object o : iterable) {
- append(o);
+ public StrBuilder appendPadding(final int length, final char padChar) {
+ if (length >= 0) {
+ ensureCapacity(size + length);
+ for (int i = 0; i < length; i++) {
+ buffer[size++] = padChar;
}
}
return this;
}
/**
- * Appends each item in an iterator to the builder without any separators.
- * Appending a null iterator will have no effect.
- * Each object is appended using {@link #append(Object)}.
+ * Appends a separator if the builder is currently non-empty.
+ * The separator is appended using {@link #append(char)}.
+ * <p>
+ * This method is useful for adding a separator each time around the
+ * loop except the first.
+ * <pre>
+ * for (Iterator it = list.iterator(); it.hasNext();){
+ * appendSeparator(',');
+ * append(it.next());
+ * }
+ * </pre>
+ * Note that for this simple example, you should use
+ * {@link #appendWithSeparators(Iterable, String)}.
*
- * @param it the iterator to append
+ * @param separator the separator to use
* @return this, to enable chaining
*/
- public StrBuilder appendAll(final Iterator<?> it) {
- if (it != null) {
- while (it.hasNext()) {
- append(it.next());
- }
+ public StrBuilder appendSeparator(final char separator) {
+ if (isNotEmpty()) {
+ append(separator);
}
return this;
}
- //-----------------------------------------------------------------------
/**
- * Appends an array placing separators between each value, but
- * not before the first or after the last.
- * Appending a null array will have no effect.
- * Each object is appended using {@link #append(Object)}.
+ * Append one of both separators to the builder
+ * If the builder is currently empty it will append the defaultIfEmpty-separator
+ * Otherwise it will append the standard-separator
*
- * @param array the array to append
- * @param separator the separator to use, null means no separator
- * @return this, to enable chaining
- */
- public StrBuilder appendWithSeparators(final Object[] array, final String separator) {
- if (array != null && array.length > 0) {
- final String sep = Objects.toString(separator, StringUtils.EMPTY);
- append(array[0]);
- for (int i = 1; i < array.length; i++) {
- append(sep);
- append(array[i]);
- }
- }
- return this;
- }
-
- /**
- * Appends an iterable placing separators between each value, but
- * not before the first or after the last.
- * Appending a null iterable will have no effect.
- * Each object is appended using {@link #append(Object)}.
- *
- * @param iterable the iterable to append
- * @param separator the separator to use, null means no separator
+ * The separator is appended using {@link #append(char)}.
+ * @param standard the separator if builder is not empty
+ * @param defaultIfEmpty the separator if builder is empty
* @return this, to enable chaining
*/
- public StrBuilder appendWithSeparators(final Iterable<?> iterable, final String separator) {
- if (iterable != null) {
- final String sep = Objects.toString(separator, StringUtils.EMPTY);
- final Iterator<?> it = iterable.iterator();
- while (it.hasNext()) {
- append(it.next());
- if (it.hasNext()) {
- append(sep);
- }
- }
+ public StrBuilder appendSeparator(final char standard, final char defaultIfEmpty) {
+ if (isNotEmpty()) {
+ append(standard);
+ } else {
+ append(defaultIfEmpty);
}
return this;
}
/**
- * Appends an iterator placing separators between each value, but
- * not before the first or after the last.
- * Appending a null iterator will have no effect.
- * Each object is appended using {@link #append(Object)}.
+ * Appends a separator to the builder if the loop index is greater than zero.
+ * The separator is appended using {@link #append(char)}.
+ * <p>
+ * This method is useful for adding a separator each time around the
+ * loop except the first.
+ * </p>
+ * <pre>
+ * for (int i = 0; i < list.size(); i++) {
+ * appendSeparator(",", i);
+ * append(list.get(i));
+ * }
+ * </pre>
+ * Note that for this simple example, you should use
+ * {@link #appendWithSeparators(Iterable, String)}.
*
- * @param it the iterator to append
- * @param separator the separator to use, null means no separator
+ * @param separator the separator to use
+ * @param loopIndex the loop index
* @return this, to enable chaining
*/
- public StrBuilder appendWithSeparators(final Iterator<?> it, final String separator) {
- if (it != null) {
- final String sep = Objects.toString(separator, StringUtils.EMPTY);
- while (it.hasNext()) {
- append(it.next());
- if (it.hasNext()) {
- append(sep);
- }
- }
+ public StrBuilder appendSeparator(final char separator, final int loopIndex) {
+ if (loopIndex > 0) {
+ append(separator);
}
return this;
}
@@ -1314,6 +1260,34 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
}
/**
+ * Appends a separator to the builder if the loop index is greater than zero.
+ * Appending a null separator will have no effect.
+ * The separator is appended using {@link #append(String)}.
+ * <p>
+ * This method is useful for adding a separator each time around the
+ * loop except the first.
+ * </p>
+ * <pre>
+ * for (int i = 0; i < list.size(); i++) {
+ * appendSeparator(",", i);
+ * append(list.get(i));
+ * }
+ * </pre>
+ * Note that for this simple example, you should use
+ * {@link #appendWithSeparators(Iterable, String)}.
+ *
+ * @param separator the separator to use, null means no separator
+ * @param loopIndex the loop index
+ * @return this, to enable chaining
+ */
+ public StrBuilder appendSeparator(final String separator, final int loopIndex) {
+ if (separator != null && loopIndex > 0) {
+ append(separator);
+ }
+ return this;
+ }
+
+ /**
* Appends one of both separators to the StrBuilder.
* If the builder is currently empty it will append the defaultIfEmpty-separator
* Otherwise it will append the standard-separator
@@ -1348,116 +1322,95 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
}
/**
- * Appends a separator if the builder is currently non-empty.
- * The separator is appended using {@link #append(char)}.
+ * Appends current contents of this {@code StrBuilder} to the
+ * provided {@link Appendable}.
* <p>
- * This method is useful for adding a separator each time around the
- * loop except the first.
- * <pre>
- * for (Iterator it = list.iterator(); it.hasNext();){
- * appendSeparator(',');
- * append(it.next());
- * }
- * </pre>
- * Note that for this simple example, you should use
- * {@link #appendWithSeparators(Iterable, String)}.
+ * This method tries to avoid doing any extra copies of contents.
*
- * @param separator the separator to use
- * @return this, to enable chaining
- */
- public StrBuilder appendSeparator(final char separator) {
- if (isNotEmpty()) {
- append(separator);
- }
- return this;
- }
-
- /**
- * Append one of both separators to the builder
- * If the builder is currently empty it will append the defaultIfEmpty-separator
- * Otherwise it will append the standard-separator
+ * @param appendable the appendable to append data to
+ * @throws IOException if an I/O error occurs
*
- * The separator is appended using {@link #append(char)}.
- * @param standard the separator if builder is not empty
- * @param defaultIfEmpty the separator if builder is empty
- * @return this, to enable chaining
+ * @see #readFrom(Readable)
*/
- public StrBuilder appendSeparator(final char standard, final char defaultIfEmpty) {
- if (isNotEmpty()) {
- append(standard);
+ public void appendTo(final Appendable appendable) throws IOException {
+ if (appendable instanceof Writer) {
+ ((Writer) appendable).write(buffer, 0, size);
+ } else if (appendable instanceof StringBuilder) {
+ ((StringBuilder) appendable).append(buffer, 0, size);
+ } else if (appendable instanceof StringBuffer) {
+ ((StringBuffer) appendable).append(buffer, 0, size);
+ } else if (appendable instanceof CharBuffer) {
+ ((CharBuffer) appendable).put(buffer, 0, size);
} else {
- append(defaultIfEmpty);
+ appendable.append(this);
}
- return this;
}
+
/**
- * Appends a separator to the builder if the loop index is greater than zero.
- * Appending a null separator will have no effect.
- * The separator is appended using {@link #append(String)}.
- * <p>
- * This method is useful for adding a separator each time around the
- * loop except the first.
- * </p>
- * <pre>
- * for (int i = 0; i < list.size(); i++) {
- * appendSeparator(",", i);
- * append(list.get(i));
- * }
- * </pre>
- * Note that for this simple example, you should use
- * {@link #appendWithSeparators(Iterable, String)}.
+ * Appends an iterable placing separators between each value, but
+ * not before the first or after the last.
+ * Appending a null iterable will have no effect.
+ * Each object is appended using {@link #append(Object)}.
*
+ * @param iterable the iterable to append
* @param separator the separator to use, null means no separator
- * @param loopIndex the loop index
* @return this, to enable chaining
*/
- public StrBuilder appendSeparator(final String separator, final int loopIndex) {
- if (separator != null && loopIndex > 0) {
- append(separator);
+ public StrBuilder appendWithSeparators(final Iterable<?> iterable, final String separator) {
+ if (iterable != null) {
+ final String sep = Objects.toString(separator, StringUtils.EMPTY);
+ final Iterator<?> it = iterable.iterator();
+ while (it.hasNext()) {
+ append(it.next());
+ if (it.hasNext()) {
+ append(sep);
+ }
+ }
}
return this;
}
/**
- * Appends a separator to the builder if the loop index is greater than zero.
- * The separator is appended using {@link #append(char)}.
- * <p>
- * This method is useful for adding a separator each time around the
- * loop except the first.
- * </p>
- * <pre>
- * for (int i = 0; i < list.size(); i++) {
- * appendSeparator(",", i);
- * append(list.get(i));
- * }
- * </pre>
- * Note that for this simple example, you should use
- * {@link #appendWithSeparators(Iterable, String)}.
+ * Appends an iterator placing separators between each value, but
+ * not before the first or after the last.
+ * Appending a null iterator will have no effect.
+ * Each object is appended using {@link #append(Object)}.
*
- * @param separator the separator to use
- * @param loopIndex the loop index
+ * @param it the iterator to append
+ * @param separator the separator to use, null means no separator
* @return this, to enable chaining
*/
- public StrBuilder appendSeparator(final char separator, final int loopIndex) {
- if (loopIndex > 0) {
- append(separator);
+ public StrBuilder appendWithSeparators(final Iterator<?> it, final String separator) {
+ if (it != null) {
+ final String sep = Objects.toString(separator, StringUtils.EMPTY);
+ while (it.hasNext()) {
+ append(it.next());
+ if (it.hasNext()) {
+ append(sep);
+ }
+ }
}
return this;
}
//-----------------------------------------------------------------------
/**
- * Appends the pad character to the builder the specified number of times.
+ * Appends an array placing separators between each value, but
+ * not before the first or after the last.
+ * Appending a null array will have no effect.
+ * Each object is appended using {@link #append(Object)}.
*
- * @param length the length to append, negative means no append
- * @param padChar the character to append
+ * @param array the array to append
+ * @param separator the separator to use, null means no separator
* @return this, to enable chaining
*/
- public StrBuilder appendPadding(final int length, final char padChar) {
- if (length >= 0) {
- ensureCapacity(size + length);
- for (int i = 0; i < length; i++) {
- buffer[size++] = padChar;
+ public StrBuilder appendWithSeparators(final Object[] array, final String separator) {
+ if (array != null && array.length > 0) {
+ final String sep = Objects.toString(separator, StringUtils.EMPTY);
+ append(array[0]);
+ for (int i = 1; i < array.length; i++) {
+ append(sep);
+ append(array[i]);
}
}
return this;
@@ -1465,799 +1418,987 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
//-----------------------------------------------------------------------
/**
- * Appends an object to the builder padding on the left to a fixed width.
- * The {@code toString} of the object is used.
- * If the object is larger than the length, the left hand side is lost.
- * If the object is null, the null text value is used.
- *
- * @param obj the object to append, null uses null text
- * @param width the fixed field width, zero or negative has no effect
- * @param padChar the pad character to use
- * @return this, to enable chaining
- */
- public StrBuilder appendFixedWidthPadLeft(final Object obj, final int width, final char padChar) {
- if (width > 0) {
- ensureCapacity(size + width);
- String str = obj == null ? getNullText() : obj.toString();
- if (str == null) {
- str = StringUtils.EMPTY;
- }
- final int strLen = str.length();
- if (strLen >= width) {
- str.getChars(strLen - width, strLen, buffer, size);
- } else {
- final int padLen = width - strLen;
- for (int i = 0; i < padLen; i++) {
- buffer[size + i] = padChar;
- }
- str.getChars(0, strLen, buffer, size + padLen);
- }
- size += width;
+ * Gets the contents of this builder as a Reader.
+ * <p>
+ * This method allows the contents of the builder to be read
+ * using any standard method that expects a Reader.
+ * <p>
+ * To use, simply create a {@code StrBuilder}, populate it with
+ * data, call {@code asReader}, and then read away.
+ * <p>
+ * The internal character array is shared between the builder and the reader.
+ * This allows you to append to the builder after creating the reader,
+ * and the changes will be picked up.
+ * Note however, that no synchronization occurs, so you must perform
+ * all operations with the builder and the reader in one thread.
+ * <p>
+ * The returned reader supports marking, and ignores the flush method.
+ *
+ * @return a reader that reads from this builder
+ */
+ public Reader asReader() {
+ return new StrBuilderReader();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Creates a tokenizer that can tokenize the contents of this builder.
+ * <p>
+ * This method allows the contents of this builder to be tokenized.
+ * The tokenizer will be setup by default to tokenize on space, tab,
+ * newline and form feed (as per StringTokenizer). These values can be
+ * changed on the tokenizer class, before retrieving the tokens.
+ * <p>
+ * The returned tokenizer is linked to this builder. You may intermix
+ * calls to the builder and tokenizer within certain limits, however
+ * there is no synchronization. Once the tokenizer has been used once,
+ * it must be {@link StrTokenizer#reset() reset} to pickup the latest
+ * changes in the builder. For example:
+ * <pre>
+ * StrBuilder b = new StrBuilder();
+ * b.append("a b ");
+ * StrTokenizer t = b.asTokenizer();
+ * String[] tokens1 = t.getTokenArray(); // returns a,b
+ * b.append("c d ");
+ * String[] tokens2 = t.getTokenArray(); // returns a,b (c and d ignored)
+ * t.reset(); // reset causes builder changes to be picked up
+ * String[] tokens3 = t.getTokenArray(); // returns a,b,c,d
+ * </pre>
+ * In addition to simply intermixing appends and tokenization, you can also
+ * call the set methods on the tokenizer to alter how it tokenizes. Just
+ * remember to call reset when you want to pickup builder changes.
+ * <p>
+ * Calling {@link StrTokenizer#reset(String)} or {@link StrTokenizer#reset(char[])}
+ * with a non-null value will break the link with the builder.
+ *
+ * @return a tokenizer that is linked to this builder
+ */
+ public StrTokenizer asTokenizer() {
+ return new StrBuilderTokenizer();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets this builder as a Writer that can be written to.
+ * <p>
+ * This method allows you to populate the contents of the builder
+ * using any standard method that takes a Writer.
+ * <p>
+ * To use, simply create a {@code StrBuilder},
+ * call {@code asWriter}, and populate away. The data is available
+ * at any time using the methods of the {@code StrBuilder}.
+ * <p>
+ * The internal character array is shared between the builder and the writer.
+ * This allows you to intermix calls that append to the builder and
+ * write using the writer and the changes will be occur correctly.
+ * Note however, that no synchronization occurs, so you must perform
+ * all operations with the builder and the writer in one thread.
+ * <p>
+ * The returned writer ignores the close and flush methods.
+ *
+ * @return a writer that populates this builder
+ */
+ public Writer asWriter() {
+ return new StrBuilderWriter();
+ }
+
+ /**
+ * Implement the {@link Builder} interface.
+ * @return The builder as a String
+ * @see #toString()
+ */
+ @Override
+ public String build() {
+ return toString();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the current size of the internal character array buffer.
+ *
+ * @return The capacity
+ */
+ public int capacity() {
+ return buffer.length;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the character at the specified index.
+ *
+ * @see #setCharAt(int, char)
+ * @see #deleteCharAt(int)
+ * @param index the index to retrieve, must be valid
+ * @return The character at the index
+ * @throws IndexOutOfBoundsException if the index is invalid
+ */
+ @Override
+ public char charAt(final int index) {
+ if (index < 0 || index >= length()) {
+ throw new StringIndexOutOfBoundsException(index);
}
+ return buffer[index];
+ }
+
+ /**
+ * Clears the string builder (convenience Collections API style method).
+ * <p>
+ * This method does not reduce the size of the internal character buffer.
+ * To do that, call {@code clear()} followed by {@link #minimizeCapacity()}.
+ * <p>
+ * This method is the same as {@link #setLength(int)} called with zero
+ * and is provided to match the API of Collections.
+ *
+ * @return this, to enable chaining
+ */
+ public StrBuilder clear() {
+ size = 0;
return this;
}
+ //-----------------------------------------------------------------------
/**
- * Appends an object to the builder padding on the left to a fixed width.
- * The {@code String.valueOf} of the {@code int} value is used.
- * If the formatted value is larger than the length, the left hand side is lost.
+ * Checks if the string builder contains the specified char.
*
- * @param value the value to append
- * @param width the fixed field width, zero or negative has no effect
- * @param padChar the pad character to use
+ * @param ch the character to find
+ * @return true if the builder contains the character
+ */
+ public boolean contains(final char ch) {
+ final char[] thisBuf = buffer;
+ for (int i = 0; i < this.size; i++) {
+ if (thisBuf[i] == ch) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Checks if the string builder contains the specified string.
+ *
+ * @param str the string to find
+ * @return true if the builder contains the string
+ */
+ public boolean contains(final String str) {
+ return indexOf(str, 0) >= 0;
+ }
+
+ /**
+ * Checks if the string builder contains a string matched using the
+ * specified matcher.
+ * <p>
+ * Matchers can be used to perform advanced searching behavior.
+ * For example you could write a matcher to search for the character
+ * 'a' followed by a number.
+ *
+ * @param matcher the matcher to use, null returns -1
+ * @return true if the matcher finds a match in the builder
+ */
+ public boolean contains(final StrMatcher matcher) {
+ return indexOf(matcher, 0) >= 0;
+ }
+ /**
+ * Deletes the characters between the two specified indices.
+ *
+ * @param startIndex the start index, inclusive, must be valid
+ * @param endIndex the end index, exclusive, must be valid except
+ * that if too large it is treated as end of string
* @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder appendFixedWidthPadLeft(final int value, final int width, final char padChar) {
- return appendFixedWidthPadLeft(String.valueOf(value), width, padChar);
+ public StrBuilder delete(final int startIndex, int endIndex) {
+ endIndex = validateRange(startIndex, endIndex);
+ final int len = endIndex - startIndex;
+ if (len > 0) {
+ deleteImpl(startIndex, endIndex, len);
+ }
+ return this;
}
+ //-----------------------------------------------------------------------
/**
- * Appends an object to the builder padding on the right to a fixed length.
- * The {@code toString} of the object is used.
- * If the object is larger than the length, the right hand side is lost.
- * If the object is null, null text value is used.
+ * Deletes the character wherever it occurs in the builder.
*
- * @param obj the object to append, null uses null text
- * @param width the fixed field width, zero or negative has no effect
- * @param padChar the pad character to use
+ * @param ch the character to delete
* @return this, to enable chaining
*/
- public StrBuilder appendFixedWidthPadRight(final Object obj, final int width, final char padChar) {
- if (width > 0) {
- ensureCapacity(size + width);
- String str = obj == null ? getNullText() : obj.toString();
- if (str == null) {
- str = StringUtils.EMPTY;
- }
- final int strLen = str.length();
- if (strLen >= width) {
- str.getChars(0, width, buffer, size);
- } else {
- final int padLen = width - strLen;
- str.getChars(0, strLen, buffer, size);
- for (int i = 0; i < padLen; i++) {
- buffer[size + strLen + i] = padChar;
+ public StrBuilder deleteAll(final char ch) {
+ for (int i = 0; i < size; i++) {
+ if (buffer[i] == ch) {
+ final int start = i;
+ while (++i < size) {
+ if (buffer[i] != ch) {
+ break;
+ }
}
+ final int len = i - start;
+ deleteImpl(start, i, len);
+ i -= len;
}
- size += width;
}
return this;
}
+ //-----------------------------------------------------------------------
/**
- * Appends an object to the builder padding on the right to a fixed length.
- * The {@code String.valueOf} of the {@code int} value is used.
- * If the object is larger than the length, the right hand side is lost.
+ * Deletes the string wherever it occurs in the builder.
*
- * @param value the value to append
- * @param width the fixed field width, zero or negative has no effect
- * @param padChar the pad character to use
+ * @param str the string to delete, null causes no action
* @return this, to enable chaining
*/
- public StrBuilder appendFixedWidthPadRight(final int value, final int width, final char padChar) {
- return appendFixedWidthPadRight(String.valueOf(value), width, padChar);
+ public StrBuilder deleteAll(final String str) {
+ final int len = str == null ? 0 : str.length();
+ if (len > 0) {
+ int index = indexOf(str, 0);
+ while (index >= 0) {
+ deleteImpl(index, index + len, len);
+ index = indexOf(str, index);
+ }
+ }
+ return this;
}
//-----------------------------------------------------------------------
/**
- * Inserts the string representation of an object into this builder.
- * Inserting null will use the stored null text value.
+ * Deletes all parts of the builder that the matcher matches.
+ * <p>
+ * Matchers can be used to perform advanced deletion behavior.
+ * For example you could write a matcher to delete all occurrences
+ * where the character 'a' is followed by a number.
*
- * @param index the index to add at, must be valid
- * @param obj the object to insert
+ * @param matcher the matcher to use to find the deletion, null causes no action
+ * @return this, to enable chaining
+ */
+ public StrBuilder deleteAll(final StrMatcher matcher) {
+ return replace(matcher, null, 0, size, -1);
+ }
+
+ /**
+ * Deletes the character at the specified index.
+ *
+ * @see #charAt(int)
+ * @see #setCharAt(int, char)
+ * @param index the index to delete
* @return this, to enable chaining
* @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder insert(final int index, final Object obj) {
- if (obj == null) {
- return insert(index, nullText);
+ public StrBuilder deleteCharAt(final int index) {
+ if (index < 0 || index >= size) {
+ throw new StringIndexOutOfBoundsException(index);
}
- return insert(index, obj.toString());
+ deleteImpl(index, index + 1, 1);
+ return this;
}
/**
- * Inserts the string into this builder.
- * Inserting null will use the stored null text value.
+ * Deletes the character wherever it occurs in the builder.
*
- * @param index the index to add at, must be valid
- * @param str the string to insert
+ * @param ch the character to delete
* @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder insert(final int index, String str) {
- validateIndex(index);
- if (str == null) {
- str = nullText;
+ public StrBuilder deleteFirst(final char ch) {
+ for (int i = 0; i < size; i++) {
+ if (buffer[i] == ch) {
+ deleteImpl(i, i + 1, 1);
+ break;
+ }
}
- if (str != null) {
- final int strLen = str.length();
- if (strLen > 0) {
- final int newSize = size + strLen;
- ensureCapacity(newSize);
- System.arraycopy(buffer, index, buffer, index + strLen, size - index);
- size = newSize;
- str.getChars(0, strLen, buffer, index);
+ return this;
+ }
+
+ /**
+ * Deletes the string wherever it occurs in the builder.
+ *
+ * @param str the string to delete, null causes no action
+ * @return this, to enable chaining
+ */
+ public StrBuilder deleteFirst(final String str) {
+ final int len = str == null ? 0 : str.length();
+ if (len > 0) {
+ final int index = indexOf(str, 0);
+ if (index >= 0) {
+ deleteImpl(index, index + len, len);
}
}
return this;
}
/**
- * Inserts the character array into this builder.
- * Inserting null will use the stored null text value.
+ * Deletes the first match within the builder using the specified matcher.
+ * <p>
+ * Matchers can be used to perform advanced deletion behavior.
+ * For example you could write a matcher to delete
+ * where the character 'a' is followed by a number.
*
- * @param index the index to add at, must be valid
- * @param chars the char array to insert
+ * @param matcher the matcher to use to find the deletion, null causes no action
* @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder insert(final int index, final char[] chars) {
- validateIndex(index);
- if (chars == null) {
- return insert(index, nullText);
+ public StrBuilder deleteFirst(final StrMatcher matcher) {
+ return replace(matcher, null, 0, size, 1);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Internal method to delete a range without validation.
+ *
+ * @param startIndex the start index, must be valid
+ * @param endIndex the end index (exclusive), must be valid
+ * @param len the length, must be valid
+ * @throws IndexOutOfBoundsException if any index is invalid
+ */
+ private void deleteImpl(final int startIndex, final int endIndex, final int len) {
+ System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex);
+ size -= len;
+ }
+
+ /**
+ * Checks whether this builder ends with the specified string.
+ * <p>
+ * Note that this method handles null input quietly, unlike String.
+ *
+ * @param str the string to search for, null returns false
+ * @return true if the builder ends with the string
+ */
+ public boolean endsWith(final String str) {
+ if (str == null) {
+ return false;
}
- final int len = chars.length;
- if (len > 0) {
- ensureCapacity(size + len);
- System.arraycopy(buffer, index, buffer, index + len, size - index);
- System.arraycopy(chars, 0, buffer, index, len);
- size += len;
+ final int len = str.length();
+ if (len == 0) {
+ return true;
+ }
+ if (len > size) {
+ return false;
+ }
+ int pos = size - len;
+ for (int i = 0; i < len; i++, pos++) {
+ if (buffer[pos] != str.charAt(i)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Checks the capacity and ensures that it is at least the size specified.
+ *
+ * @param capacity the capacity to ensure
+ * @return this, to enable chaining
+ */
+ public StrBuilder ensureCapacity(final int capacity) {
+ if (capacity > buffer.length) {
+ final char[] old = buffer;
+ buffer = new char[capacity * 2];
+ System.arraycopy(old, 0, buffer, 0, size);
+ }
+ return this;
+ }
+
+ /**
+ * Checks the contents of this builder against another to see if they
+ * contain the same character content.
+ *
+ * @param obj the object to check, null returns false
+ * @return true if the builders contain the same characters in the same order
+ */
+ @Override
+ public boolean equals(final Object obj) {
+ return obj instanceof StrBuilder
+ && equals((StrBuilder) obj);
+ }
+
+ /**
+ * Checks the contents of this builder against another to see if they
+ * contain the same character content.
+ *
+ * @param other the object to check, null returns false
+ * @return true if the builders contain the same characters in the same order
+ */
+ public boolean equals(final StrBuilder other) {
+ if (this == other) {
+ return true;
+ }
+ if (other == null) {
+ return false;
+ }
+ if (this.size != other.size) {
+ return false;
}
- return this;
+ final char[] thisBuf = this.buffer;
+ final char[] otherBuf = other.buffer;
+ for (int i = size - 1; i >= 0; i--) {
+ if (thisBuf[i] != otherBuf[i]) {
+ return false;
+ }
+ }
+ return true;
}
/**
- * Inserts part of the character array into this builder.
- * Inserting null will use the stored null text value.
+ * Checks the contents of this builder against another to see if they
+ * contain the same character content ignoring case.
*
- * @param index the index to add at, must be valid
- * @param chars the char array to insert
- * @param offset the offset into the character array to start at, must be valid
- * @param length the length of the character array part to copy, must be positive
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @param other the object to check, null returns false
+ * @return true if the builders contain the same characters in the same order
*/
- public StrBuilder insert(final int index, final char[] chars, final int offset, final int length) {
- validateIndex(index);
- if (chars == null) {
- return insert(index, nullText);
- }
- if (offset < 0 || offset > chars.length) {
- throw new StringIndexOutOfBoundsException("Invalid offset: " + offset);
+ public boolean equalsIgnoreCase(final StrBuilder other) {
+ if (this == other) {
+ return true;
}
- if (length < 0 || offset + length > chars.length) {
- throw new StringIndexOutOfBoundsException("Invalid length: " + length);
+ if (this.size != other.size) {
+ return false;
}
- if (length > 0) {
- ensureCapacity(size + length);
- System.arraycopy(buffer, index, buffer, index + length, size - index);
- System.arraycopy(chars, offset, buffer, index, length);
- size += length;
+ final char[] thisBuf = this.buffer;
+ final char[] otherBuf = other.buffer;
+ for (int i = size - 1; i >= 0; i--) {
+ final char c1 = thisBuf[i];
+ final char c2 = otherBuf[i];
+ if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) {
+ return false;
+ }
}
- return this;
+ return true;
}
/**
- * Inserts the value into this builder.
+ * Copies the character array into the specified array.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param destination the destination array, null will cause an array to be created
+ * @return The input array, unless that was null or too small
*/
- public StrBuilder insert(int index, final boolean value) {
- validateIndex(index);
- if (value) {
- ensureCapacity(size + 4);
- System.arraycopy(buffer, index, buffer, index + 4, size - index);
- buffer[index++] = 't';
- buffer[index++] = 'r';
- buffer[index++] = 'u';
- buffer[index] = 'e';
- size += 4;
- } else {
- ensureCapacity(size + 5);
- System.arraycopy(buffer, index, buffer, index + 5, size - index);
- buffer[index++] = 'f';
- buffer[index++] = 'a';
- buffer[index++] = 'l';
- buffer[index++] = 's';
- buffer[index] = 'e';
- size += 5;
+ public char[] getChars(char[] destination) {
+ final int len = length();
+ if (destination == null || destination.length < len) {
+ destination = new char[len];
}
- return this;
+ System.arraycopy(buffer, 0, destination, 0, len);
+ return destination;
}
/**
- * Inserts the value into this builder.
+ * Copies the character array into the specified array.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param startIndex first index to copy, inclusive, must be valid
+ * @param endIndex last index, exclusive, must be valid
+ * @param destination the destination array, must not be null or too small
+ * @param destinationIndex the index to start copying in destination
+ * @throws NullPointerException if the array is null
+ * @throws IndexOutOfBoundsException if any index is invalid
*/
- public StrBuilder insert(final int index, final char value) {
- validateIndex(index);
- ensureCapacity(size + 1);
- System.arraycopy(buffer, index, buffer, index + 1, size - index);
- buffer[index] = value;
- size++;
- return this;
+ public void getChars(final int startIndex,
+ final int endIndex,
+ final char[] destination,
+ final int destinationIndex) {
+ if (startIndex < 0) {
+ throw new StringIndexOutOfBoundsException(startIndex);
+ }
+ if (endIndex < 0 || endIndex > length()) {
+ throw new StringIndexOutOfBoundsException(endIndex);
+ }
+ if (startIndex > endIndex) {
+ throw new StringIndexOutOfBoundsException("end < start");
+ }
+ System.arraycopy(buffer, startIndex, destination, destinationIndex, endIndex - startIndex);
}
+ //-----------------------------------------------------------------------
/**
- * Inserts the value into this builder.
+ * Gets the text to be appended when a new line is added.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @return The new line text, null means use system default
*/
- public StrBuilder insert(final int index, final int value) {
- return insert(index, String.valueOf(value));
+ public String getNewLineText() {
+ return newLine;
}
+ //-----------------------------------------------------------------------
/**
- * Inserts the value into this builder.
+ * Gets the text to be appended when null is added.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @return The null text, null means no append
*/
- public StrBuilder insert(final int index, final long value) {
- return insert(index, String.valueOf(value));
+ public String getNullText() {
+ return nullText;
}
/**
- * Inserts the value into this builder.
+ * Gets a suitable hash code for this builder.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @return a hash code
*/
- public StrBuilder insert(final int index, final float value) {
- return insert(index, String.valueOf(value));
+ @Override
+ public int hashCode() {
+ final char[] buf = buffer;
+ int hash = 0;
+ for (int i = size - 1; i >= 0; i--) {
+ hash = 31 * hash + buf[i];
+ }
+ return hash;
}
+ //-----------------------------------------------------------------------
/**
- * Inserts the value into this builder.
+ * Searches the string builder to find the first reference to the specified char.
*
- * @param index the index to add at, must be valid
- * @param value the value to insert
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param ch the character to find
+ * @return The first index of the character, or -1 if not found
*/
- public StrBuilder insert(final int index, final double value) {
- return insert(index, String.valueOf(value));
+ public int indexOf(final char ch) {
+ return indexOf(ch, 0);
}
- //-----------------------------------------------------------------------
/**
- * Internal method to delete a range without validation.
+ * Searches the string builder to find the first reference to the specified char.
*
- * @param startIndex the start index, must be valid
- * @param endIndex the end index (exclusive), must be valid
- * @param len the length, must be valid
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @param ch the character to find
+ * @param startIndex the index to start at, invalid index rounded to edge
+ * @return The first index of the character, or -1 if not found
*/
- private void deleteImpl(final int startIndex, final int endIndex, final int len) {
- System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex);
- size -= len;
+ public int indexOf(final char ch, int startIndex) {
+ startIndex = startIndex < 0 ? 0 : startIndex;
+ if (startIndex >= size) {
+ return -1;
+ }
+ final char[] thisBuf = buffer;
+ for (int i = startIndex; i < size; i++) {
+ if (thisBuf[i] == ch) {
+ return i;
+ }
+ }
+ return -1;
}
/**
- * Deletes the characters between the two specified indices.
+ * Searches the string builder to find the first reference to the specified string.
+ * <p>
+ * Note that a null input string will return -1, whereas the JDK throws an exception.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except
- * that if too large it is treated as end of string
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param str the string to find, null returns -1
+ * @return The first index of the string, or -1 if not found
*/
- public StrBuilder delete(final int startIndex, int endIndex) {
- endIndex = validateRange(startIndex, endIndex);
- final int len = endIndex - startIndex;
- if (len > 0) {
- deleteImpl(startIndex, endIndex, len);
- }
- return this;
+ public int indexOf(final String str) {
+ return indexOf(str, 0);
}
- //-----------------------------------------------------------------------
/**
- * Deletes the character wherever it occurs in the builder.
+ * Searches the string builder to find the first reference to the specified
+ * string starting searching from the given index.
+ * <p>
+ * Note that a null input string will return -1, whereas the JDK throws an exception.
*
- * @param ch the character to delete
- * @return this, to enable chaining
+ * @param str the string to find, null returns -1
+ * @param startIndex the index to start at, invalid index rounded to edge
+ * @return The first index of the string, or -1 if not found
*/
- public StrBuilder deleteAll(final char ch) {
- for (int i = 0; i < size; i++) {
- if (buffer[i] == ch) {
- final int start = i;
- while (++i < size) {
- if (buffer[i] != ch) {
- break;
- }
+ public int indexOf(final String str, int startIndex) {
+ startIndex = startIndex < 0 ? 0 : startIndex;
+ if (str == null || startIndex >= size) {
+ return -1;
+ }
+ final int strLen = str.length();
+ if (strLen == 1) {
+ return indexOf(str.charAt(0), startIndex);
+ }
+ if (strLen == 0) {
+ return startIndex;
+ }
+ if (strLen > size) {
+ return -1;
+ }
+ final char[] thisBuf = buffer;
+ final int len = size - strLen + 1;
+ outer:
+ for (int i = startIndex; i < len; i++) {
+ for (int j = 0; j < strLen; j++) {
+ if (str.charAt(j) != thisBuf[i + j]) {
+ continue outer;
}
- final int len = i - start;
- deleteImpl(start, i, len);
- i -= len;
}
+ return i;
}
- return this;
+ return -1;
}
/**
- * Deletes the character wherever it occurs in the builder.
+ * Searches the string builder using the matcher to find the first match.
+ * <p>
+ * Matchers can be used to perform advanced searching behavior.
+ * For example you could write a matcher to find the character 'a'
+ * followed by a number.
*
- * @param ch the character to delete
- * @return this, to enable chaining
+ * @param matcher the matcher to use, null returns -1
+ * @return The first index matched, or -1 if not found
*/
- public StrBuilder deleteFirst(final char ch) {
- for (int i = 0; i < size; i++) {
- if (buffer[i] == ch) {
- deleteImpl(i, i + 1, 1);
- break;
- }
- }
- return this;
+ public int indexOf(final StrMatcher matcher) {
+ return indexOf(matcher, 0);
}
- //-----------------------------------------------------------------------
/**
- * Deletes the string wherever it occurs in the builder.
+ * Searches the string builder using the matcher to find the first
+ * match searching from the given index.
+ * <p>
+ * Matchers can be used to perform advanced searching behavior.
+ * For example you could write a matcher to find the character 'a'
+ * followed by a number.
*
- * @param str the string to delete, null causes no action
- * @return this, to enable chaining
+ * @param matcher the matcher to use, null returns -1
+ * @param startIndex the index to start at, invalid index rounded to edge
+ * @return The first index matched, or -1 if not found
*/
- public StrBuilder deleteAll(final String str) {
- final int len = str == null ? 0 : str.length();
- if (len > 0) {
- int index = indexOf(str, 0);
- while (index >= 0) {
- deleteImpl(index, index + len, len);
- index = indexOf(str, index);
+ public int indexOf(final StrMatcher matcher, int startIndex) {
+ startIndex = startIndex < 0 ? 0 : startIndex;
+ if (matcher == null || startIndex >= size) {
+ return -1;
+ }
+ final int len = size;
+ final char[] buf = buffer;
+ for (int i = startIndex; i < len; i++) {
+ if (matcher.isMatch(buf, i, startIndex, len) > 0) {
+ return i;
}
}
- return this;
+ return -1;
}
/**
- * Deletes the string wherever it occurs in the builder.
+ * Inserts the value into this builder.
*
- * @param str the string to delete, null causes no action
+ * @param index the index to add at, must be valid
+ * @param value the value to insert
* @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder deleteFirst(final String str) {
- final int len = str == null ? 0 : str.length();
- if (len > 0) {
- final int index = indexOf(str, 0);
- if (index >= 0) {
- deleteImpl(index, index + len, len);
- }
+ public StrBuilder insert(int index, final boolean value) {
+ validateIndex(index);
+ if (value) {
+ ensureCapacity(size + 4);
+ System.arraycopy(buffer, index, buffer, index + 4, size - index);
+ buffer[index++] = 't';
+ buffer[index++] = 'r';
+ buffer[index++] = 'u';
+ buffer[index] = 'e';
+ size += 4;
+ } else {
+ ensureCapacity(size + 5);
+ System.arraycopy(buffer, index, buffer, index + 5, size - index);
+ buffer[index++] = 'f';
+ buffer[index++] = 'a';
+ buffer[index++] = 'l';
+ buffer[index++] = 's';
+ buffer[index] = 'e';
+ size += 5;
}
return this;
}
- //-----------------------------------------------------------------------
/**
- * Deletes all parts of the builder that the matcher matches.
- * <p>
- * Matchers can be used to perform advanced deletion behavior.
- * For example you could write a matcher to delete all occurrences
- * where the character 'a' is followed by a number.
+ * Inserts the value into this builder.
*
- * @param matcher the matcher to use to find the deletion, null causes no action
+ * @param index the index to add at, must be valid
+ * @param value the value to insert
* @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder deleteAll(final StrMatcher matcher) {
- return replace(matcher, null, 0, size, -1);
+ public StrBuilder insert(final int index, final char value) {
+ validateIndex(index);
+ ensureCapacity(size + 1);
+ System.arraycopy(buffer, index, buffer, index + 1, size - index);
+ buffer[index] = value;
+ size++;
+ return this;
}
/**
- * Deletes the first match within the builder using the specified matcher.
- * <p>
- * Matchers can be used to perform advanced deletion behavior.
- * For example you could write a matcher to delete
- * where the character 'a' is followed by a number.
+ * Inserts the character array into this builder.
+ * Inserting null will use the stored null text value.
*
- * @param matcher the matcher to use to find the deletion, null causes no action
+ * @param index the index to add at, must be valid
+ * @param chars the char array to insert
* @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder deleteFirst(final StrMatcher matcher) {
- return replace(matcher, null, 0, size, 1);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Internal method to delete a range without validation.
- *
- * @param startIndex the start index, must be valid
- * @param endIndex the end index (exclusive), must be valid
- * @param removeLen the length to remove (endIndex - startIndex), must be valid
- * @param insertStr the string to replace with, null means delete range
- * @param insertLen the length of the insert string, must be valid
- * @throws IndexOutOfBoundsException if any index is invalid
- */
- private void replaceImpl(final int startIndex,
- final int endIndex,
- final int removeLen,
- final String insertStr,
- final int insertLen) {
- final int newSize = size - removeLen + insertLen;
- if (insertLen != removeLen) {
- ensureCapacity(newSize);
- System.arraycopy(buffer, endIndex, buffer, startIndex + insertLen, size - endIndex);
- size = newSize;
+ public StrBuilder insert(final int index, final char[] chars) {
+ validateIndex(index);
+ if (chars == null) {
+ return insert(index, nullText);
}
- if (insertLen > 0) {
- insertStr.getChars(0, insertLen, buffer, startIndex);
+ final int len = chars.length;
+ if (len > 0) {
+ ensureCapacity(size + len);
+ System.arraycopy(buffer, index, buffer, index + len, size - index);
+ System.arraycopy(chars, 0, buffer, index, len);
+ size += len;
}
+ return this;
}
/**
- * Replaces a portion of the string builder with another string.
- * The length of the inserted string does not have to match the removed length.
+ * Inserts part of the character array into this builder.
+ * Inserting null will use the stored null text value.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except
- * that if too large it is treated as end of string
- * @param replaceStr the string to replace with, null means delete range
+ * @param index the index to add at, must be valid
+ * @param chars the char array to insert
+ * @param offset the offset into the character array to start at, must be valid
+ * @param length the length of the character array part to copy, must be positive
* @return this, to enable chaining
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IndexOutOfBoundsException if any index is invalid
*/
- public StrBuilder replace(final int startIndex, int endIndex, final String replaceStr) {
- endIndex = validateRange(startIndex, endIndex);
- final int insertLen = replaceStr == null ? 0 : replaceStr.length();
- replaceImpl(startIndex, endIndex, endIndex - startIndex, replaceStr, insertLen);
+ public StrBuilder insert(final int index, final char[] chars, final int offset, final int length) {
+ validateIndex(index);
+ if (chars == null) {
+ return insert(index, nullText);
+ }
+ if (offset < 0 || offset > chars.length) {
+ throw new StringIndexOutOfBoundsException("Invalid offset: " + offset);
+ }
+ if (length < 0 || offset + length > chars.length) {
+ throw new StringIndexOutOfBoundsException("Invalid length: " + length);
+ }
+ if (length > 0) {
+ ensureCapacity(size + length);
+ System.arraycopy(buffer, index, buffer, index + length, size - index);
+ System.arraycopy(chars, offset, buffer, index, length);
+ size += length;
+ }
return this;
}
- //-----------------------------------------------------------------------
/**
- * Replaces the search character with the replace character
- * throughout the builder.
+ * Inserts the value into this builder.
*
- * @param search the search character
- * @param replace the replace character
+ * @param index the index to add at, must be valid
+ * @param value the value to insert
* @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder replaceAll(final char search, final char replace) {
- if (search != replace) {
- for (int i = 0; i < size; i++) {
- if (buffer[i] == search) {
- buffer[i] = replace;
- }
- }
- }
- return this;
+ public StrBuilder insert(final int index, final double value) {
+ return insert(index, String.valueOf(value));
}
/**
- * Replaces the first instance of the search character with the
- * replace character in the builder.
+ * Inserts the value into this builder.
*
- * @param search the search character
- * @param replace the replace character
+ * @param index the index to add at, must be valid
+ * @param value the value to insert
* @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder replaceFirst(final char search, final char replace) {
- if (search != replace) {
- for (int i = 0; i < size; i++) {
- if (buffer[i] == search) {
- buffer[i] = replace;
- break;
- }
- }
- }
- return this;
+ public StrBuilder insert(final int index, final float value) {
+ return insert(index, String.valueOf(value));
}
- //-----------------------------------------------------------------------
/**
- * Replaces the search string with the replace string throughout the builder.
+ * Inserts the value into this builder.
*
- * @param searchStr the search string, null causes no action to occur
- * @param replaceStr the replace string, null is equivalent to an empty string
+ * @param index the index to add at, must be valid
+ * @param value the value to insert
* @return this, to enable chaining
- */
- public StrBuilder replaceAll(final String searchStr, final String replaceStr) {
- final int searchLen = searchStr == null ? 0 : searchStr.length();
- if (searchLen > 0) {
- final int replaceLen = replaceStr == null ? 0 : replaceStr.length();
- int index = indexOf(searchStr, 0);
- while (index >= 0) {
- replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen);
- index = indexOf(searchStr, index + replaceLen);
- }
- }
- return this;
+ * @throws IndexOutOfBoundsException if the index is invalid
+ */
+ public StrBuilder insert(final int index, final int value) {
+ return insert(index, String.valueOf(value));
}
/**
- * Replaces the first instance of the search string with the replace string.
+ * Inserts the value into this builder.
*
- * @param searchStr the search string, null causes no action to occur
- * @param replaceStr the replace string, null is equivalent to an empty string
+ * @param index the index to add at, must be valid
+ * @param value the value to insert
* @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder replaceFirst(final String searchStr, final String replaceStr) {
- final int searchLen = searchStr == null ? 0 : searchStr.length();
- if (searchLen > 0) {
- final int index = indexOf(searchStr, 0);
- if (index >= 0) {
- final int replaceLen = replaceStr == null ? 0 : replaceStr.length();
- replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen);
- }
- }
- return this;
+ public StrBuilder insert(final int index, final long value) {
+ return insert(index, String.valueOf(value));
}
//-----------------------------------------------------------------------
/**
- * Replaces all matches within the builder with the replace string.
- * <p>
- * Matchers can be used to perform advanced replace behavior.
- * For example you could write a matcher to replace all occurrences
- * where the character 'a' is followed by a number.
+ * Inserts the string representation of an object into this builder.
+ * Inserting null will use the stored null text value.
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the replace string, null is equivalent to an empty string
+ * @param index the index to add at, must be valid
+ * @param obj the object to insert
* @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder replaceAll(final StrMatcher matcher, final String replaceStr) {
- return replace(matcher, replaceStr, 0, size, -1);
+ public StrBuilder insert(final int index, final Object obj) {
+ if (obj == null) {
+ return insert(index, nullText);
+ }
+ return insert(index, obj.toString());
}
/**
- * Replaces the first match within the builder with the replace string.
- * <p>
- * Matchers can be used to perform advanced replace behavior.
- * For example you could write a matcher to replace
- * where the character 'a' is followed by a number.
+ * Inserts the string into this builder.
+ * Inserting null will use the stored null text value.
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the replace string, null is equivalent to an empty string
+ * @param index the index to add at, must be valid
+ * @param str the string to insert
* @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public StrBuilder replaceFirst(final StrMatcher matcher, final String replaceStr) {
- return replace(matcher, replaceStr, 0, size, 1);
+ public StrBuilder insert(final int index, String str) {
+ validateIndex(index);
+ if (str == null) {
+ str = nullText;
+ }
+ if (str != null) {
+ final int strLen = str.length();
+ if (strLen > 0) {
+ final int newSize = size + strLen;
+ ensureCapacity(newSize);
+ System.arraycopy(buffer, index, buffer, index + strLen, size - index);
+ size = newSize;
+ str.getChars(0, strLen, buffer, index);
+ }
+ }
+ return this;
}
- // -----------------------------------------------------------------------
/**
- * Advanced search and replaces within the builder using a matcher.
+ * Checks is the string builder is empty (convenience Collections API style method).
* <p>
- * Matchers can be used to perform advanced behavior.
- * For example you could write a matcher to delete all occurrences
- * where the character 'a' is followed by a number.
+ * This method is the same as checking {@link #length()} and is provided to match the
+ * API of Collections.
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the string to replace the match with, null is a delete
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except
- * that if too large it is treated as end of string
- * @param replaceCount the number of times to replace, -1 for replace all
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if start index is invalid
+ * @return {@code true} if the size is {@code 0}.
*/
- public StrBuilder replace(
- final StrMatcher matcher, final String replaceStr,
- final int startIndex, int endIndex, final int replaceCount) {
- endIndex = validateRange(startIndex, endIndex);
- return replaceImpl(matcher, replaceStr, startIndex, endIndex, replaceCount);
+ public boolean isEmpty() {
+ return size == 0;
}
/**
- * Replaces within the builder using a matcher.
+ * Checks is the string builder is not empty (convenience Collections API style method).
* <p>
- * Matchers can be used to perform advanced behavior.
- * For example you could write a matcher to delete all occurrences
- * where the character 'a' is followed by a number.
+ * This method is the same as checking {@link #length()} and is provided to match the
+ * API of Collections.
*
- * @param matcher the matcher to use to find the deletion, null causes no action
- * @param replaceStr the string to replace the match with, null is a delete
- * @param from the start index, must be valid
- * @param to the end index (exclusive), must be valid
- * @param replaceCount the number of times to replace, -1 for replace all
- * @return this, to enable chaining
- * @throws IndexOutOfBoundsException if any index is invalid
+ * @return {@code true} if the size is greater than {@code 0}.
+ * @since 1.10.0
*/
- private StrBuilder replaceImpl(
- final StrMatcher matcher, final String replaceStr,
- final int from, int to, int replaceCount) {
- if (matcher == null || size == 0) {
- return this;
- }
- final int replaceLen = replaceStr == null ? 0 : replaceStr.length();
- for (int i = from; i < to && replaceCount != 0; i++) {
- final char[] buf = buffer;
- final int removeLen = matcher.isMatch(buf, i, from, to);
- if (removeLen > 0) {
- replaceImpl(i, i + removeLen, removeLen, replaceStr, replaceLen);
- to = to - removeLen + replaceLen;
- i = i + replaceLen - 1;
- if (replaceCount > 0) {
- replaceCount--;
- }
- }
- }
- return this;
+ public boolean isNotEmpty() {
+ return size > 0;
}
//-----------------------------------------------------------------------
/**
- * Reverses the string builder placing each character in the opposite index.
+ * Searches the string builder to find the last reference to the specified char.
*
- * @return this, to enable chaining
+ * @param ch the character to find
+ * @return The last index of the character, or -1 if not found
*/
- public StrBuilder reverse() {
- if (size == 0) {
- return this;
- }
-
- final int half = size / 2;
- final char[] buf = buffer;
- for (int leftIdx = 0, rightIdx = size - 1; leftIdx < half; leftIdx++, rightIdx--) {
- final char swap = buf[leftIdx];
- buf[leftIdx] = buf[rightIdx];
- buf[rightIdx] = swap;
- }
- return this;
+ public int lastIndexOf(final char ch) {
+ return lastIndexOf(ch, size - 1);
}
- //-----------------------------------------------------------------------
/**
- * Trims the builder by removing characters less than or equal to a space
- * from the beginning and end.
+ * Searches the string builder to find the last reference to the specified char.
*
- * @return this, to enable chaining
+ * @param ch the character to find
+ * @param startIndex the index to start at, invalid index rounded to edge
+ * @return The last index of the character, or -1 if not found
*/
- public StrBuilder trim() {
- if (size == 0) {
- return this;
- }
- int len = size;
- final char[] buf = buffer;
- int pos = 0;
- while (pos < len && buf[pos] <= ' ') {
- pos++;
- }
- while (pos < len && buf[len - 1] <= ' ') {
- len--;
- }
- if (len < size) {
- delete(len, size);
+ public int lastIndexOf(final char ch, int startIndex) {
+ startIndex = startIndex >= size ? size - 1 : startIndex;
+ if (startIndex < 0) {
+ return -1;
}
- if (pos > 0) {
- delete(0, pos);
+ for (int i = startIndex; i >= 0; i--) {
+ if (buffer[i] == ch) {
+ return i;
+ }
}
- return this;
+ return -1;
}
- //-----------------------------------------------------------------------
/**
- * Checks whether this builder starts with the specified string.
+ * Searches the string builder to find the last reference to the specified string.
* <p>
- * Note that this method handles null input quietly, unlike String.
+ * Note that a null input string will return -1, whereas the JDK throws an exception.
*
- * @param str the string to search for, null returns false
- * @return true if the builder starts with the string
+ * @param str the string to find, null returns -1
+ * @return The last index of the string, or -1 if not found
*/
- public boolean startsWith(final String str) {
- if (str == null) {
- return false;
- }
- final int len = str.length();
- if (len == 0) {
- return true;
- }
- if (len > size) {
- return false;
- }
- for (int i = 0; i < len; i++) {
- if (buffer[i] != str.charAt(i)) {
- return false;
- }
- }
- return true;
+ public int lastIndexOf(final String str) {
+ return lastIndexOf(str, size - 1);
}
/**
- * Checks whether this builder ends with the specified string.
+ * Searches the string builder to find the last reference to the specified
+ * string starting searching from the given index.
* <p>
- * Note that this method handles null input quietly, unlike String.
+ * Note that a null input string will return -1, whereas the JDK throws an exception.
*
- * @param str the string to search for, null returns false
- * @return true if the builder ends with the string
+ * @param str the string to find, null returns -1
+ * @param startIndex the index to start at, invalid index rounded to edge
+ * @return The last index of the string, or -1 if not found
*/
- public boolean endsWith(final String str) {
- if (str == null) {
- return false;
- }
- final int len = str.length();
- if (len == 0) {
- return true;
- }
- if (len > size) {
- return false;
+ public int lastIndexOf(final String str, int startIndex) {
+ startIndex = startIndex >= size ? size - 1 : startIndex;
+ if (str == null || startIndex < 0) {
+ return -1;
}
- int pos = size - len;
- for (int i = 0; i < len; i++, pos++) {
- if (buffer[pos] != str.charAt(i)) {
- return false;
+ final int strLen = str.length();
+ if (strLen > 0 && strLen <= size) {
+ if (strLen == 1) {
+ return lastIndexOf(str.charAt(0), startIndex);
+ }
+
+ outer:
+ for (int i = startIndex - strLen + 1; i >= 0; i--) {
+ for (int j = 0; j < strLen; j++) {
+ if (str.charAt(j) != buffer[i + j]) {
+ continue outer;
+ }
+ }
+ return i;
}
- }
- return true;
- }
- //-----------------------------------------------------------------------
- /**
- * {@inheritDoc}
- */
- @Override
- public CharSequence subSequence(final int startIndex, final int endIndex) {
- if (startIndex < 0) {
- throw new StringIndexOutOfBoundsException(startIndex);
- }
- if (endIndex > size) {
- throw new StringIndexOutOfBoundsException(endIndex);
- }
- if (startIndex > endIndex) {
- throw new StringIndexOutOfBoundsException(endIndex - startIndex);
- }
- return substring(startIndex, endIndex);
+ } else if (strLen == 0) {
+ return startIndex;
+ }
+ return -1;
}
/**
- * Extracts a portion of this string builder as a string.
+ * Searches the string builder using the matcher to find the last match.
+ * <p>
+ * Matchers can be used to perform advanced searching behavior.
+ * For example you could write a matcher to find the character 'a'
+ * followed by a number.
*
- * @param start the start index, inclusive, must be valid
- * @return The new string
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param matcher the matcher to use, null returns -1
+ * @return The last index matched, or -1 if not found
*/
- public String substring(final int start) {
- return substring(start, size);
+ public int lastIndexOf(final StrMatcher matcher) {
+ return lastIndexOf(matcher, size);
}
/**
- * Extracts a portion of this string builder as a string.
+ * Searches the string builder using the matcher to find the last
+ * match searching from the given index.
* <p>
- * Note: This method treats an endIndex greater than the length of the
- * builder as equal to the length of the builder, and continues
- * without error, unlike StringBuffer or String.
+ * Matchers can be used to perform advanced searching behavior.
+ * For example you could write a matcher to find the character 'a'
+ * followed by a number.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except
- * that if too large it is treated as end of string
- * @return The new string
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @param matcher the matcher to use, null returns -1
+ * @param startIndex the index to start at, invalid index rounded to edge
+ * @return The last index matched, or -1 if not found
*/
- public String substring(final int startIndex, int endIndex) {
- endIndex = validateRange(startIndex, endIndex);
- return new String(buffer, startIndex, endIndex - startIndex);
+ public int lastIndexOf(final StrMatcher matcher, int startIndex) {
+ startIndex = startIndex >= size ? size - 1 : startIndex;
+ if (matcher == null || startIndex < 0) {
+ return -1;
+ }
+ final char[] buf = buffer;
+ final int endIndex = startIndex + 1;
+ for (int i = startIndex; i >= 0; i--) {
+ if (matcher.isMatch(buf, i, 0, endIndex) > 0) {
+ return i;
+ }
+ }
+ return -1;
}
/**
@@ -2282,26 +2423,15 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
}
}
+ //-----------------------------------------------------------------------
/**
- * Extracts the rightmost characters from the string builder without
- * throwing an exception.
- * <p>
- * This method extracts the right {@code length} characters from
- * the builder. If this many characters are not available, the whole
- * builder is returned. Thus the returned string may be shorter than the
- * length requested.
+ * Gets the length of the string builder.
*
- * @param length the number of characters to extract, negative returns empty string
- * @return The new string
+ * @return The length
*/
- public String rightString(final int length) {
- if (length <= 0) {
- return StringUtils.EMPTY;
- } else if (length >= size) {
- return new String(buffer, 0, size);
- } else {
- return new String(buffer, size - length, length);
- }
+ @Override
+ public int length() {
+ return size;
}
/**
@@ -2333,483 +2463,512 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
return new String(buffer, index, length);
}
+ /**
+ * Minimizes the capacity to the actual length of the string.
+ *
+ * @return this, to enable chaining
+ */
+ public StrBuilder minimizeCapacity() {
+ if (buffer.length > length()) {
+ final char[] old = buffer;
+ buffer = new char[length()];
+ System.arraycopy(old, 0, buffer, 0, size);
+ }
+ return this;
+ }
+
//-----------------------------------------------------------------------
/**
- * Checks if the string builder contains the specified char.
+ * If possible, reads chars from the provided {@link Readable} directly into underlying
+ * character buffer without making extra copies.
*
- * @param ch the character to find
- * @return true if the builder contains the character
+ * @param readable object to read from
+ * @return The number of characters read
+ * @throws IOException if an I/O error occurs
+ *
+ * @see #appendTo(Appendable)
*/
- public boolean contains(final char ch) {
- final char[] thisBuf = buffer;
- for (int i = 0; i < this.size; i++) {
- if (thisBuf[i] == ch) {
- return true;
+ public int readFrom(final Readable readable) throws IOException {
+ final int oldSize = size;
+ if (readable instanceof Reader) {
+ final Reader r = (Reader) readable;
+ ensureCapacity(size + 1);
+ int read;
+ while ((read = r.read(buffer, size, buffer.length - size)) != -1) {
+ size += read;
+ ensureCapacity(size + 1);
+ }
+ } else if (readable instanceof CharBuffer) {
+ final CharBuffer cb = (CharBuffer) readable;
+ final int remaining = cb.remaining();
+ ensureCapacity(size + remaining);
+ cb.get(buffer, size, remaining);
+ size += remaining;
+ } else {
+ while (true) {
+ ensureCapacity(size + 1);
+ final CharBuffer buf = CharBuffer.wrap(buffer, size, buffer.length - size);
+ final int read = readable.read(buf);
+ if (read == -1) {
+ break;
+ }
+ size += read;
}
}
- return false;
+ return size - oldSize;
}
/**
- * Checks if the string builder contains the specified string.
+ * Replaces a portion of the string builder with another string.
+ * The length of the inserted string does not have to match the removed length.
*
- * @param str the string to find
- * @return true if the builder contains the string
+ * @param startIndex the start index, inclusive, must be valid
+ * @param endIndex the end index, exclusive, must be valid except
+ * that if too large it is treated as end of string
+ * @param replaceStr the string to replace with, null means delete range
+ * @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public boolean contains(final String str) {
- return indexOf(str, 0) >= 0;
+ public StrBuilder replace(final int startIndex, int endIndex, final String replaceStr) {
+ endIndex = validateRange(startIndex, endIndex);
+ final int insertLen = replaceStr == null ? 0 : replaceStr.length();
+ replaceImpl(startIndex, endIndex, endIndex - startIndex, replaceStr, insertLen);
+ return this;
}
+ // -----------------------------------------------------------------------
/**
- * Checks if the string builder contains a string matched using the
- * specified matcher.
+ * Advanced search and replaces within the builder using a matcher.
* <p>
- * Matchers can be used to perform advanced searching behavior.
- * For example you could write a matcher to search for the character
- * 'a' followed by a number.
+ * Matchers can be used to perform advanced behavior.
+ * For example you could write a matcher to delete all occurrences
+ * where the character 'a' is followed by a number.
*
- * @param matcher the matcher to use, null returns -1
- * @return true if the matcher finds a match in the builder
+ * @param matcher the matcher to use to find the deletion, null causes no action
+ * @param replaceStr the string to replace the match with, null is a delete
+ * @param startIndex the start index, inclusive, must be valid
+ * @param endIndex the end index, exclusive, must be valid except
+ * that if too large it is treated as end of string
+ * @param replaceCount the number of times to replace, -1 for replace all
+ * @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if start index is invalid
*/
- public boolean contains(final StrMatcher matcher) {
- return indexOf(matcher, 0) >= 0;
+ public StrBuilder replace(
+ final StrMatcher matcher, final String replaceStr,
+ final int startIndex, int endIndex, final int replaceCount) {
+ endIndex = validateRange(startIndex, endIndex);
+ return replaceImpl(matcher, replaceStr, startIndex, endIndex, replaceCount);
}
//-----------------------------------------------------------------------
/**
- * Searches the string builder to find the first reference to the specified char.
+ * Replaces the search character with the replace character
+ * throughout the builder.
*
- * @param ch the character to find
- * @return The first index of the character, or -1 if not found
+ * @param search the search character
+ * @param replace the replace character
+ * @return this, to enable chaining
*/
- public int indexOf(final char ch) {
- return indexOf(ch, 0);
+ public StrBuilder replaceAll(final char search, final char replace) {
+ if (search != replace) {
+ for (int i = 0; i < size; i++) {
+ if (buffer[i] == search) {
+ buffer[i] = replace;
+ }
+ }
+ }
+ return this;
}
+ //-----------------------------------------------------------------------
/**
- * Searches the string builder to find the first reference to the specified char.
+ * Replaces the search string with the replace string throughout the builder.
*
- * @param ch the character to find
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The first index of the character, or -1 if not found
+ * @param searchStr the search string, null causes no action to occur
+ * @param replaceStr the replace string, null is equivalent to an empty string
+ * @return this, to enable chaining
*/
- public int indexOf(final char ch, int startIndex) {
- startIndex = startIndex < 0 ? 0 : startIndex;
- if (startIndex >= size) {
- return -1;
- }
- final char[] thisBuf = buffer;
- for (int i = startIndex; i < size; i++) {
- if (thisBuf[i] == ch) {
- return i;
+ public StrBuilder replaceAll(final String searchStr, final String replaceStr) {
+ final int searchLen = searchStr == null ? 0 : searchStr.length();
+ if (searchLen > 0) {
+ final int replaceLen = replaceStr == null ? 0 : replaceStr.length();
+ int index = indexOf(searchStr, 0);
+ while (index >= 0) {
+ replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen);
+ index = indexOf(searchStr, index + replaceLen);
}
}
- return -1;
+ return this;
}
+ //-----------------------------------------------------------------------
/**
- * Searches the string builder to find the first reference to the specified string.
+ * Replaces all matches within the builder with the replace string.
* <p>
- * Note that a null input string will return -1, whereas the JDK throws an exception.
+ * Matchers can be used to perform advanced replace behavior.
+ * For example you could write a matcher to replace all occurrences
+ * where the character 'a' is followed by a number.
*
- * @param str the string to find, null returns -1
- * @return The first index of the string, or -1 if not found
+ * @param matcher the matcher to use to find the deletion, null causes no action
+ * @param replaceStr the replace string, null is equivalent to an empty string
+ * @return this, to enable chaining
*/
- public int indexOf(final String str) {
- return indexOf(str, 0);
+ public StrBuilder replaceAll(final StrMatcher matcher, final String replaceStr) {
+ return replace(matcher, replaceStr, 0, size, -1);
}
/**
- * Searches the string builder to find the first reference to the specified
- * string starting searching from the given index.
- * <p>
- * Note that a null input string will return -1, whereas the JDK throws an exception.
+ * Replaces the first instance of the search character with the
+ * replace character in the builder.
*
- * @param str the string to find, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The first index of the string, or -1 if not found
+ * @param search the search character
+ * @param replace the replace character
+ * @return this, to enable chaining
*/
- public int indexOf(final String str, int startIndex) {
- startIndex = startIndex < 0 ? 0 : startIndex;
- if (str == null || startIndex >= size) {
- return -1;
- }
- final int strLen = str.length();
- if (strLen == 1) {
- return indexOf(str.charAt(0), startIndex);
- }
- if (strLen == 0) {
- return startIndex;
- }
- if (strLen > size) {
- return -1;
- }
- final char[] thisBuf = buffer;
- final int len = size - strLen + 1;
- outer:
- for (int i = startIndex; i < len; i++) {
- for (int j = 0; j < strLen; j++) {
- if (str.charAt(j) != thisBuf[i + j]) {
- continue outer;
+ public StrBuilder replaceFirst(final char search, final char replace) {
+ if (search != replace) {
+ for (int i = 0; i < size; i++) {
+ if (buffer[i] == search) {
+ buffer[i] = replace;
+ break;
}
}
- return i;
}
- return -1;
+ return this;
}
/**
- * Searches the string builder using the matcher to find the first match.
- * <p>
- * Matchers can be used to perform advanced searching behavior.
- * For example you could write a matcher to find the character 'a'
- * followed by a number.
+ * Replaces the first instance of the search string with the replace string.
*
- * @param matcher the matcher to use, null returns -1
- * @return The first index matched, or -1 if not found
+ * @param searchStr the search string, null causes no action to occur
+ * @param replaceStr the replace string, null is equivalent to an empty string
+ * @return this, to enable chaining
*/
- public int indexOf(final StrMatcher matcher) {
- return indexOf(matcher, 0);
+ public StrBuilder replaceFirst(final String searchStr, final String replaceStr) {
+ final int searchLen = searchStr == null ? 0 : searchStr.length();
+ if (searchLen > 0) {
+ final int index = indexOf(searchStr, 0);
+ if (index >= 0) {
+ final int replaceLen = replaceStr == null ? 0 : replaceStr.length();
+ replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen);
+ }
+ }
+ return this;
}
/**
- * Searches the string builder using the matcher to find the first
- * match searching from the given index.
+ * Replaces the first match within the builder with the replace string.
* <p>
- * Matchers can be used to perform advanced searching behavior.
- * For example you could write a matcher to find the character 'a'
- * followed by a number.
+ * Matchers can be used to perform advanced replace behavior.
+ * For example you could write a matcher to replace
+ * where the character 'a' is followed by a number.
*
- * @param matcher the matcher to use, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The first index matched, or -1 if not found
+ * @param matcher the matcher to use to find the deletion, null causes no action
+ * @param replaceStr the replace string, null is equivalent to an empty string
+ * @return this, to enable chaining
*/
- public int indexOf(final StrMatcher matcher, int startIndex) {
- startIndex = startIndex < 0 ? 0 : startIndex;
- if (matcher == null || startIndex >= size) {
- return -1;
- }
- final int len = size;
- final char[] buf = buffer;
- for (int i = startIndex; i < len; i++) {
- if (matcher.isMatch(buf, i, startIndex, len) > 0) {
- return i;
- }
- }
- return -1;
+ public StrBuilder replaceFirst(final StrMatcher matcher, final String replaceStr) {
+ return replace(matcher, replaceStr, 0, size, 1);
}
//-----------------------------------------------------------------------
/**
- * Searches the string builder to find the last reference to the specified char.
+ * Internal method to delete a range without validation.
*
- * @param ch the character to find
- * @return The last index of the character, or -1 if not found
+ * @param startIndex the start index, must be valid
+ * @param endIndex the end index (exclusive), must be valid
+ * @param removeLen the length to remove (endIndex - startIndex), must be valid
+ * @param insertStr the string to replace with, null means delete range
+ * @param insertLen the length of the insert string, must be valid
+ * @throws IndexOutOfBoundsException if any index is invalid
*/
- public int lastIndexOf(final char ch) {
- return lastIndexOf(ch, size - 1);
+ private void replaceImpl(final int startIndex,
+ final int endIndex,
+ final int removeLen,
+ final String insertStr,
+ final int insertLen) {
+ final int newSize = size - removeLen + insertLen;
+ if (insertLen != removeLen) {
+ ensureCapacity(newSize);
+ System.arraycopy(buffer, endIndex, buffer, startIndex + insertLen, size - endIndex);
+ size = newSize;
+ }
+ if (insertLen > 0) {
+ insertStr.getChars(0, insertLen, buffer, startIndex);
+ }
}
/**
- * Searches the string builder to find the last reference to the specified char.
+ * Replaces within the builder using a matcher.
+ * <p>
+ * Matchers can be used to perform advanced behavior.
+ * For example you could write a matcher to delete all occurrences
+ * where the character 'a' is followed by a number.
*
- * @param ch the character to find
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The last index of the character, or -1 if not found
+ * @param matcher the matcher to use to find the deletion, null causes no action
+ * @param replaceStr the string to replace the match with, null is a delete
+ * @param from the start index, must be valid
+ * @param to the end index (exclusive), must be valid
+ * @param replaceCount the number of times to replace, -1 for replace all
+ * @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if any index is invalid
*/
- public int lastIndexOf(final char ch, int startIndex) {
- startIndex = startIndex >= size ? size - 1 : startIndex;
- if (startIndex < 0) {
- return -1;
+ private StrBuilder replaceImpl(
+ final StrMatcher matcher, final String replaceStr,
+ final int from, int to, int replaceCount) {
+ if (matcher == null || size == 0) {
+ return this;
}
- for (int i = startIndex; i >= 0; i--) {
- if (buffer[i] == ch) {
- return i;
+ final int replaceLen = replaceStr == null ? 0 : replaceStr.length();
+ for (int i = from; i < to && replaceCount != 0; i++) {
+ final char[] buf = buffer;
+ final int removeLen = matcher.isMatch(buf, i, from, to);
+ if (removeLen > 0) {
+ replaceImpl(i, i + removeLen, removeLen, replaceStr, replaceLen);
+ to = to - removeLen + replaceLen;
+ i = i + replaceLen - 1;
+ if (replaceCount > 0) {
+ replaceCount--;
+ }
}
}
- return -1;
+ return this;
}
+ //-----------------------------------------------------------------------
/**
- * Searches the string builder to find the last reference to the specified string.
- * <p>
- * Note that a null input string will return -1, whereas the JDK throws an exception.
+ * Reverses the string builder placing each character in the opposite index.
*
- * @param str the string to find, null returns -1
- * @return The last index of the string, or -1 if not found
+ * @return this, to enable chaining
*/
- public int lastIndexOf(final String str) {
- return lastIndexOf(str, size - 1);
+ public StrBuilder reverse() {
+ if (size == 0) {
+ return this;
+ }
+
+ final int half = size / 2;
+ final char[] buf = buffer;
+ for (int leftIdx = 0, rightIdx = size - 1; leftIdx < half; leftIdx++, rightIdx--) {
+ final char swap = buf[leftIdx];
+ buf[leftIdx] = buf[rightIdx];
+ buf[rightIdx] = swap;
+ }
+ return this;
}
/**
- * Searches the string builder to find the last reference to the specified
- * string starting searching from the given index.
+ * Extracts the rightmost characters from the string builder without
+ * throwing an exception.
* <p>
- * Note that a null input string will return -1, whereas the JDK throws an exception.
+ * This method extracts the right {@code length} characters from
+ * the builder. If this many characters are not available, the whole
+ * builder is returned. Thus the returned string may be shorter than the
+ * length requested.
*
- * @param str the string to find, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The last index of the string, or -1 if not found
+ * @param length the number of characters to extract, negative returns empty string
+ * @return The new string
*/
- public int lastIndexOf(final String str, int startIndex) {
- startIndex = startIndex >= size ? size - 1 : startIndex;
- if (str == null || startIndex < 0) {
- return -1;
- }
- final int strLen = str.length();
- if (strLen > 0 && strLen <= size) {
- if (strLen == 1) {
- return lastIndexOf(str.charAt(0), startIndex);
- }
-
- outer:
- for (int i = startIndex - strLen + 1; i >= 0; i--) {
- for (int j = 0; j < strLen; j++) {
- if (str.charAt(j) != buffer[i + j]) {
- continue outer;
- }
- }
- return i;
- }
-
- } else if (strLen == 0) {
- return startIndex;
+ public String rightString(final int length) {
+ if (length <= 0) {
+ return StringUtils.EMPTY;
+ } else if (length >= size) {
+ return new String(buffer, 0, size);
+ } else {
+ return new String(buffer, size - length, length);
}
- return -1;
}
/**
- * Searches the string builder using the matcher to find the last match.
- * <p>
- * Matchers can be used to perform advanced searching behavior.
- * For example you could write a matcher to find the character 'a'
- * followed by a number.
+ * Sets the character at the specified index.
*
- * @param matcher the matcher to use, null returns -1
- * @return The last index matched, or -1 if not found
+ * @see #charAt(int)
+ * @see #deleteCharAt(int)
+ * @param index the index to set
+ * @param ch the new character
+ * @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public int lastIndexOf(final StrMatcher matcher) {
- return lastIndexOf(matcher, size);
+ public StrBuilder setCharAt(final int index, final char ch) {
+ if (index < 0 || index >= length()) {
+ throw new StringIndexOutOfBoundsException(index);
+ }
+ buffer[index] = ch;
+ return this;
}
/**
- * Searches the string builder using the matcher to find the last
- * match searching from the given index.
- * <p>
- * Matchers can be used to perform advanced searching behavior.
- * For example you could write a matcher to find the character 'a'
- * followed by a number.
+ * Updates the length of the builder by either dropping the last characters
+ * or adding filler of Unicode zero.
*
- * @param matcher the matcher to use, null returns -1
- * @param startIndex the index to start at, invalid index rounded to edge
- * @return The last index matched, or -1 if not found
+ * @param length the length to set to, must be zero or positive
+ * @return this, to enable chaining
+ * @throws IndexOutOfBoundsException if the length is negative
*/
- public int lastIndexOf(final StrMatcher matcher, int startIndex) {
- startIndex = startIndex >= size ? size - 1 : startIndex;
- if (matcher == null || startIndex < 0) {
- return -1;
+ public StrBuilder setLength(final int length) {
+ if (length < 0) {
+ throw new StringIndexOutOfBoundsException(length);
}
- final char[] buf = buffer;
- final int endIndex = startIndex + 1;
- for (int i = startIndex; i >= 0; i--) {
- if (matcher.isMatch(buf, i, 0, endIndex) > 0) {
- return i;
+ if (length < size) {
+ size = length;
+ } else if (length > size) {
+ ensureCapacity(length);
+ final int oldEnd = size;
+ final int newEnd = length;
+ size = length;
+ for (int i = oldEnd; i < newEnd; i++) {
+ buffer[i] = '\0';
}
}
- return -1;
+ return this;
}
- //-----------------------------------------------------------------------
/**
- * Creates a tokenizer that can tokenize the contents of this builder.
- * <p>
- * This method allows the contents of this builder to be tokenized.
- * The tokenizer will be setup by default to tokenize on space, tab,
- * newline and form feed (as per StringTokenizer). These values can be
- * changed on the tokenizer class, before retrieving the tokens.
- * <p>
- * The returned tokenizer is linked to this builder. You may intermix
- * calls to the builder and tokenizer within certain limits, however
- * there is no synchronization. Once the tokenizer has been used once,
- * it must be {@link StrTokenizer#reset() reset} to pickup the latest
- * changes in the builder. For example:
- * <pre>
- * StrBuilder b = new StrBuilder();
- * b.append("a b ");
- * StrTokenizer t = b.asTokenizer();
- * String[] tokens1 = t.getTokenArray(); // returns a,b
- * b.append("c d ");
- * String[] tokens2 = t.getTokenArray(); // returns a,b (c and d ignored)
- * t.reset(); // reset causes builder changes to be picked up
- * String[] tokens3 = t.getTokenArray(); // returns a,b,c,d
- * </pre>
- * In addition to simply intermixing appends and tokenization, you can also
- * call the set methods on the tokenizer to alter how it tokenizes. Just
- * remember to call reset when you want to pickup builder changes.
- * <p>
- * Calling {@link StrTokenizer#reset(String)} or {@link StrTokenizer#reset(char[])}
- * with a non-null value will break the link with the builder.
+ * Sets the text to be appended when a new line is added.
*
- * @return a tokenizer that is linked to this builder
+ * @param newLine the new line text, null means use system default
+ * @return this, to enable chaining
*/
- public StrTokenizer asTokenizer() {
- return new StrBuilderTokenizer();
+ public StrBuilder setNewLineText(final String newLine) {
+ this.newLine = newLine;
+ return this;
}
- //-----------------------------------------------------------------------
/**
- * Gets the contents of this builder as a Reader.
- * <p>
- * This method allows the contents of the builder to be read
- * using any standard method that expects a Reader.
- * <p>
- * To use, simply create a {@code StrBuilder}, populate it with
- * data, call {@code asReader}, and then read away.
- * <p>
- * The internal character array is shared between the builder and the reader.
- * This allows you to append to the builder after creating the reader,
- * and the changes will be picked up.
- * Note however, that no synchronization occurs, so you must perform
- * all operations with the builder and the reader in one thread.
- * <p>
- * The returned reader supports marking, and ignores the flush method.
+ * Sets the text to be appended when null is added.
*
- * @return a reader that reads from this builder
+ * @param nullText the null text, null means no append
+ * @return this, to enable chaining
*/
- public Reader asReader() {
- return new StrBuilderReader();
+ public StrBuilder setNullText(String nullText) {
+ if (nullText != null && nullText.isEmpty()) {
+ nullText = null;
+ }
+ this.nullText = nullText;
+ return this;
}
//-----------------------------------------------------------------------
/**
- * Gets this builder as a Writer that can be written to.
- * <p>
- * This method allows you to populate the contents of the builder
- * using any standard method that takes a Writer.
- * <p>
- * To use, simply create a {@code StrBuilder},
- * call {@code asWriter}, and populate away. The data is available
- * at any time using the methods of the {@code StrBuilder}.
- * <p>
- * The internal character array is shared between the builder and the writer.
- * This allows you to intermix calls that append to the builder and
- * write using the writer and the changes will be occur correctly.
- * Note however, that no synchronization occurs, so you must perform
- * all operations with the builder and the writer in one thread.
+ * Gets the length of the string builder.
* <p>
- * The returned writer ignores the close and flush methods.
+ * This method is the same as {@link #length()} and is provided to match the
+ * API of Collections.
*
- * @return a writer that populates this builder
+ * @return The length
*/
- public Writer asWriter() {
- return new StrBuilderWriter();
+ public int size() {
+ return size;
}
+ //-----------------------------------------------------------------------
/**
- * Appends current contents of this {@code StrBuilder} to the
- * provided {@link Appendable}.
+ * Checks whether this builder starts with the specified string.
* <p>
- * This method tries to avoid doing any extra copies of contents.
- *
- * @param appendable the appendable to append data to
- * @throws IOException if an I/O error occurs
+ * Note that this method handles null input quietly, unlike String.
*
- * @see #readFrom(Readable)
+ * @param str the string to search for, null returns false
+ * @return true if the builder starts with the string
*/
- public void appendTo(final Appendable appendable) throws IOException {
- if (appendable instanceof Writer) {
- ((Writer) appendable).write(buffer, 0, size);
- } else if (appendable instanceof StringBuilder) {
- ((StringBuilder) appendable).append(buffer, 0, size);
- } else if (appendable instanceof StringBuffer) {
- ((StringBuffer) appendable).append(buffer, 0, size);
- } else if (appendable instanceof CharBuffer) {
- ((CharBuffer) appendable).put(buffer, 0, size);
- } else {
- appendable.append(this);
+ public boolean startsWith(final String str) {
+ if (str == null) {
+ return false;
}
- }
-
- /**
- * Checks the contents of this builder against another to see if they
- * contain the same character content ignoring case.
- *
- * @param other the object to check, null returns false
- * @return true if the builders contain the same characters in the same order
- */
- public boolean equalsIgnoreCase(final StrBuilder other) {
- if (this == other) {
+ final int len = str.length();
+ if (len == 0) {
return true;
}
- if (this.size != other.size) {
+ if (len > size) {
return false;
}
- final char[] thisBuf = this.buffer;
- final char[] otherBuf = other.buffer;
- for (int i = size - 1; i >= 0; i--) {
- final char c1 = thisBuf[i];
- final char c2 = otherBuf[i];
- if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) {
+ for (int i = 0; i < len; i++) {
+ if (buffer[i] != str.charAt(i)) {
return false;
}
}
return true;
}
+ //-----------------------------------------------------------------------
/**
- * Checks the contents of this builder against another to see if they
- * contain the same character content.
+ * {@inheritDoc}
+ */
+ @Override
+ public CharSequence subSequence(final int startIndex, final int endIndex) {
+ if (startIndex < 0) {
+ throw new StringIndexOutOfBoundsException(startIndex);
+ }
+ if (endIndex > size) {
+ throw new StringIndexOutOfBoundsException(endIndex);
+ }
+ if (startIndex > endIndex) {
+ throw new StringIndexOutOfBoundsException(endIndex - startIndex);
+ }
+ return substring(startIndex, endIndex);
+ }
+
+ /**
+ * Extracts a portion of this string builder as a string.
*
- * @param other the object to check, null returns false
- * @return true if the builders contain the same characters in the same order
+ * @param start the start index, inclusive, must be valid
+ * @return The new string
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public boolean equals(final StrBuilder other) {
- if (this == other) {
- return true;
- }
- if (other == null) {
- return false;
- }
- if (this.size != other.size) {
- return false;
- }
- final char[] thisBuf = this.buffer;
- final char[] otherBuf = other.buffer;
- for (int i = size - 1; i >= 0; i--) {
- if (thisBuf[i] != otherBuf[i]) {
- return false;
- }
- }
- return true;
+ public String substring(final int start) {
+ return substring(start, size);
}
/**
- * Checks the contents of this builder against another to see if they
- * contain the same character content.
+ * Extracts a portion of this string builder as a string.
+ * <p>
+ * Note: This method treats an endIndex greater than the length of the
+ * builder as equal to the length of the builder, and continues
+ * without error, unlike StringBuffer or String.
*
- * @param obj the object to check, null returns false
- * @return true if the builders contain the same characters in the same order
+ * @param startIndex the start index, inclusive, must be valid
+ * @param endIndex the end index, exclusive, must be valid except
+ * that if too large it is treated as end of string
+ * @return The new string
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- @Override
- public boolean equals(final Object obj) {
- return obj instanceof StrBuilder
- && equals((StrBuilder) obj);
+ public String substring(final int startIndex, int endIndex) {
+ endIndex = validateRange(startIndex, endIndex);
+ return new String(buffer, startIndex, endIndex - startIndex);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Copies the builder's character array into a new character array.
+ *
+ * @return a new array that represents the contents of the builder
+ */
+ public char[] toCharArray() {
+ if (size == 0) {
+ return ArrayUtils.EMPTY_CHAR_ARRAY;
+ }
+ final char[] chars = new char[size];
+ System.arraycopy(buffer, 0, chars, 0, size);
+ return chars;
}
/**
- * Gets a suitable hash code for this builder.
+ * Copies part of the builder's character array into a new character array.
*
- * @return a hash code
+ * @param startIndex the start index, inclusive, must be valid
+ * @param endIndex the end index, exclusive, must be valid except that
+ * if too large it is treated as end of string
+ * @return a new array that holds part of the contents of the builder
+ * @throws IndexOutOfBoundsException if startIndex is invalid,
+ * or if endIndex is invalid (but endIndex greater than size is valid)
*/
- @Override
- public int hashCode() {
- final char[] buf = buffer;
- int hash = 0;
- for (int i = size - 1; i >= 0; i--) {
- hash = 31 * hash + buf[i];
+ public char[] toCharArray(final int startIndex, int endIndex) {
+ endIndex = validateRange(startIndex, endIndex);
+ final int len = endIndex - startIndex;
+ if (len == 0) {
+ return ArrayUtils.EMPTY_CHAR_ARRAY;
}
- return hash;
+ final char[] chars = new char[len];
+ System.arraycopy(buffer, startIndex, chars, 0, len);
+ return chars;
}
//-----------------------------------------------------------------------
@@ -2847,37 +3006,33 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
return new StringBuilder(size).append(buffer, 0, size);
}
- /**
- * Implement the {@link Builder} interface.
- * @return The builder as a String
- * @see #toString()
- */
- @Override
- public String build() {
- return toString();
- }
-
//-----------------------------------------------------------------------
/**
- * Validates parameters defining a range of the builder.
+ * Trims the builder by removing characters less than or equal to a space
+ * from the beginning and end.
*
- * @param startIndex the start index, inclusive, must be valid
- * @param endIndex the end index, exclusive, must be valid except
- * that if too large it is treated as end of string
- * @return The new string
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @return this, to enable chaining
*/
- protected int validateRange(final int startIndex, int endIndex) {
- if (startIndex < 0) {
- throw new StringIndexOutOfBoundsException(startIndex);
+ public StrBuilder trim() {
+ if (size == 0) {
+ return this;
}
- if (endIndex > size) {
- endIndex = size;
+ int len = size;
+ final char[] buf = buffer;
+ int pos = 0;
+ while (pos < len && buf[pos] <= ' ') {
+ pos++;
}
- if (startIndex > endIndex) {
- throw new StringIndexOutOfBoundsException("end < start");
+ while (pos < len && buf[len - 1] <= ' ') {
+ len--;
}
- return endIndex;
+ if (len < size) {
+ delete(len, size);
+ }
+ if (pos > 0) {
+ delete(0, pos);
+ }
+ return this;
}
/**
@@ -2894,180 +3049,25 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build
//-----------------------------------------------------------------------
/**
- * Inner class to allow StrBuilder to operate as a tokenizer.
- */
- class StrBuilderTokenizer extends StrTokenizer {
-
- /**
- * Default constructor.
- */
- StrBuilderTokenizer() {
- }
-
- /** {@inheritDoc} */
- @Override
- protected List<String> tokenize(final char[] chars, final int offset, final int count) {
- if (chars == null) {
- return super.tokenize(
- StrBuilder.this.buffer, 0, StrBuilder.this.size());
- }
- return super.tokenize(chars, offset, count);
- }
-
- /** {@inheritDoc} */
- @Override
- public String getContent() {
- final String str = super.getContent();
- if (str == null) {
- return StrBuilder.this.toString();
- }
- return str;
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Inner class to allow StrBuilder to operate as a reader.
- */
- class StrBuilderReader extends Reader {
- /** The current stream position. */
- private int pos;
- /** The last mark position. */
- private int mark;
-
- /**
- * Default constructor.
- */
- StrBuilderReader() {
- }
-
- /** {@inheritDoc} */
- @Override
- public void close() {
- // do nothing
- }
-
- /** {@inheritDoc} */
- @Override
- public int read() {
- if (!ready()) {
- return -1;
- }
- return StrBuilder.this.charAt(pos++);
- }
-
- /** {@inheritDoc} */
- @Override
- public int read(final char[] b, final int off, int len) {
- if (off < 0 || len < 0 || off > b.length
- || off + len > b.length || off + len < 0) {
- throw new IndexOutOfBoundsException();
- }
- if (len == 0) {
- return 0;
- }
- if (pos >= StrBuilder.this.size()) {
- return -1;
- }
- if (pos + len > size()) {
- len = StrBuilder.this.size() - pos;
- }
- StrBuilder.this.getChars(pos, pos + len, b, off);
- pos += len;
- return len;
- }
-
- /** {@inheritDoc} */
- @Override
- public long skip(long n) {
- if (pos + n > StrBuilder.this.size()) {
- n = StrBuilder.this.size() - pos;
- }
- if (n < 0) {
- return 0;
- }
- pos += n;
- return n;
- }
-
- /** {@inheritDoc} */
- @Override
- public boolean ready() {
- return pos < StrBuilder.this.size();
- }
-
- /** {@inheritDoc} */
- @Override
- public boolean markSupported() {
- return true;
- }
-
- /** {@inheritDoc} */
- @Override
- public void mark(final int readAheadLimit) {
- mark = pos;
- }
-
- /** {@inheritDoc} */
- @Override
- public void reset() {
- pos = mark;
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Inner class to allow StrBuilder to operate as a writer.
+ * Validates parameters defining a range of the builder.
+ *
+ * @param startIndex the start index, inclusive, must be valid
+ * @param endIndex the end index, exclusive, must be valid except
+ * that if too large it is treated as end of string
+ * @return The new string
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- class StrBuilderWriter extends Writer {
-
- /**
- * Default constructor.
- */
- StrBuilderWriter() {
- }
-
- /** {@inheritDoc} */
- @Override
- public void close() {
- // do nothing
- }
-
- /** {@inheritDoc} */
- @Override
- public void flush() {
- // do nothing
- }
-
- /** {@inheritDoc} */
- @Override
- public void write(final int c) {
- StrBuilder.this.append((char) c);
- }
-
- /** {@inheritDoc} */
- @Override
- public void write(final char[] cbuf) {
- StrBuilder.this.append(cbuf);
- }
-
- /** {@inheritDoc} */
- @Override
- public void write(final char[] cbuf, final int off, final int len) {
- StrBuilder.this.append(cbuf, off, len);
+ protected int validateRange(final int startIndex, int endIndex) {
+ if (startIndex < 0) {
+ throw new StringIndexOutOfBoundsException(startIndex);
}
-
- /** {@inheritDoc} */
- @Override
- public void write(final String str) {
- StrBuilder.this.append(str);
+ if (endIndex > size) {
+ endIndex = size;
}
-
- /** {@inheritDoc} */
- @Override
- public void write(final String str, final int off, final int len) {
- StrBuilder.this.append(str, off, len);
+ if (startIndex > endIndex) {
+ throw new StringIndexOutOfBoundsException("end < start");
}
+ return endIndex;
}
}
diff --git a/src/main/java/org/apache/commons/text/StrTokenizer.java b/src/main/java/org/apache/commons/text/StrTokenizer.java
index 2de1735..f1e1b74 100644
--- a/src/main/java/org/apache/commons/text/StrTokenizer.java
+++ b/src/main/java/org/apache/commons/text/StrTokenizer.java
@@ -108,29 +108,6 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
TSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);
}
- /** The text to work on. */
- private char[] chars;
- /** The parsed tokens. */
- private String[] tokens;
- /** The current iteration position. */
- private int tokenPos;
-
- /** The delimiter matcher. */
- private StrMatcher delimMatcher = StrMatcher.splitMatcher();
- /** The quote matcher. */
- private StrMatcher quoteMatcher = StrMatcher.noneMatcher();
- /** The ignored matcher. */
- private StrMatcher ignoredMatcher = StrMatcher.noneMatcher();
- /** The trimmer matcher. */
- private StrMatcher trimmerMatcher = StrMatcher.noneMatcher();
-
- /** Whether to return empty tokens as null. */
- private boolean emptyAsNull;
- /** Whether to ignore empty tokens. */
- private boolean ignoreEmptyTokens = true;
-
- //-----------------------------------------------------------------------
-
/**
* Returns a clone of {@code CSV_TOKENIZER_PROTOTYPE}.
*
@@ -139,7 +116,6 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
private static StrTokenizer getCSVClone() {
return (StrTokenizer) CSV_TOKENIZER_PROTOTYPE.clone();
}
-
/**
* Gets a new tokenizer instance which parses Comma Separated Value strings
* initializing it with the given input. The default for CSV processing
@@ -152,7 +128,6 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
public static StrTokenizer getCSVInstance() {
return getCSVClone();
}
-
/**
* Gets a new tokenizer instance which parses Comma Separated Value strings
* initializing it with the given input. The default for CSV processing
@@ -162,7 +137,7 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
* @param input the text to parse
* @return a new tokenizer instance which parses Comma Separated Value strings
*/
- public static StrTokenizer getCSVInstance(final String input) {
+ public static StrTokenizer getCSVInstance(final char[] input) {
final StrTokenizer tok = getCSVClone();
tok.reset(input);
return tok;
@@ -177,12 +152,11 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
* @param input the text to parse
* @return a new tokenizer instance which parses Comma Separated Value strings
*/
- public static StrTokenizer getCSVInstance(final char[] input) {
+ public static StrTokenizer getCSVInstance(final String input) {
final StrTokenizer tok = getCSVClone();
tok.reset(input);
return tok;
}
-
/**
* Returns a clone of {@code TSV_TOKENIZER_PROTOTYPE}.
*
@@ -191,8 +165,6 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
private static StrTokenizer getTSVClone() {
return (StrTokenizer) TSV_TOKENIZER_PROTOTYPE.clone();
}
-
-
/**
* Gets a new tokenizer instance which parses Tab Separated Value strings.
* The default for CSV processing will be trim whitespace from both ends
@@ -204,7 +176,6 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
public static StrTokenizer getTSVInstance() {
return getTSVClone();
}
-
/**
* Gets a new tokenizer instance which parses Tab Separated Value strings.
* The default for CSV processing will be trim whitespace from both ends
@@ -212,7 +183,7 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
* @param input the string to parse
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
- public static StrTokenizer getTSVInstance(final String input) {
+ public static StrTokenizer getTSVInstance(final char[] input) {
final StrTokenizer tok = getTSVClone();
tok.reset(input);
return tok;
@@ -225,11 +196,40 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
* @param input the string to parse
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
- public static StrTokenizer getTSVInstance(final char[] input) {
+ public static StrTokenizer getTSVInstance(final String input) {
final StrTokenizer tok = getTSVClone();
tok.reset(input);
return tok;
}
+ /** The text to work on. */
+ private char[] chars;
+
+ //-----------------------------------------------------------------------
+
+ /** The parsed tokens. */
+ private String[] tokens;
+
+ /** The current iteration position. */
+ private int tokenPos;
+
+ /** The delimiter matcher. */
+ private StrMatcher delimMatcher = StrMatcher.splitMatcher();
+
+ /** The quote matcher. */
+ private StrMatcher quoteMatcher = StrMatcher.noneMatcher();
+
+ /** The ignored matcher. */
+ private StrMatcher ignoredMatcher = StrMatcher.noneMatcher();
+
+
+ /** The trimmer matcher. */
+ private StrMatcher trimmerMatcher = StrMatcher.noneMatcher();
+
+ /** Whether to return empty tokens as null. */
+ private boolean emptyAsNull;
+
+ /** Whether to ignore empty tokens. */
+ private boolean ignoreEmptyTokens = true;
//-----------------------------------------------------------------------
/**
@@ -246,71 +246,71 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
* Constructs a tokenizer splitting on space, tab, newline and form feed
* as per StringTokenizer.
*
- * @param input the string which is to be parsed
+ * @param input the string which is to be parsed, not cloned
*/
- public StrTokenizer(final String input) {
- if (input != null) {
- chars = input.toCharArray();
+ public StrTokenizer(final char[] input) {
+ if (input == null) {
+ this.chars = null;
} else {
- chars = null;
+ this.chars = input.clone();
}
}
/**
- * Constructs a tokenizer splitting on the specified delimiter character.
+ * Constructs a tokenizer splitting on the specified character.
*
- * @param input the string which is to be parsed
- * @param delim the field delimiter character
+ * @param input the string which is to be parsed, not cloned
+ * @param delim the field delimiter character
*/
- public StrTokenizer(final String input, final char delim) {
+ public StrTokenizer(final char[] input, final char delim) {
this(input);
setDelimiterChar(delim);
}
/**
- * Constructs a tokenizer splitting on the specified delimiter string.
+ * Constructs a tokenizer splitting on the specified delimiter character
+ * and handling quotes using the specified quote character.
*
- * @param input the string which is to be parsed
- * @param delim the field delimiter string
+ * @param input the string which is to be parsed, not cloned
+ * @param delim the field delimiter character
+ * @param quote the field quoted string character
*/
- public StrTokenizer(final String input, final String delim) {
- this(input);
- setDelimiterString(delim);
+ public StrTokenizer(final char[] input, final char delim, final char quote) {
+ this(input, delim);
+ setQuoteChar(quote);
}
/**
- * Constructs a tokenizer splitting using the specified delimiter matcher.
+ * Constructs a tokenizer splitting on the specified string.
*
- * @param input the string which is to be parsed
- * @param delim the field delimiter matcher
+ * @param input the string which is to be parsed, not cloned
+ * @param delim the field delimiter string
*/
- public StrTokenizer(final String input, final StrMatcher delim) {
+ public StrTokenizer(final char[] input, final String delim) {
this(input);
- setDelimiterMatcher(delim);
+ setDelimiterString(delim);
}
/**
- * Constructs a tokenizer splitting on the specified delimiter character
- * and handling quotes using the specified quote character.
+ * Constructs a tokenizer splitting using the specified delimiter matcher.
*
- * @param input the string which is to be parsed
- * @param delim the field delimiter character
- * @param quote the field quoted string character
+ * @param input the string which is to be parsed, not cloned
+ * @param delim the field delimiter matcher
*/
- public StrTokenizer(final String input, final char delim, final char quote) {
- this(input, delim);
- setQuoteChar(quote);
+ public StrTokenizer(final char[] input, final StrMatcher delim) {
+ this(input);
+ setDelimiterMatcher(delim);
}
/**
* Constructs a tokenizer splitting using the specified delimiter matcher
* and handling quotes using the specified quote matcher.
*
- * @param input the string which is to be parsed
- * @param delim the field delimiter matcher
- * @param quote the field quoted string matcher
+ * @param input the string which is to be parsed, not cloned
+ * @param delim the field delimiter character
+ * @param quote the field quoted string character
*/
- public StrTokenizer(final String input, final StrMatcher delim, final StrMatcher quote) {
+ public StrTokenizer(final char[] input, final StrMatcher delim, final StrMatcher quote) {
this(input, delim);
setQuoteMatcher(quote);
}
@@ -319,119 +319,215 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
* Constructs a tokenizer splitting on space, tab, newline and form feed
* as per StringTokenizer.
*
- * @param input the string which is to be parsed, not cloned
+ * @param input the string which is to be parsed
*/
- public StrTokenizer(final char[] input) {
- if (input == null) {
- this.chars = null;
+ public StrTokenizer(final String input) {
+ if (input != null) {
+ chars = input.toCharArray();
} else {
- this.chars = input.clone();
+ chars = null;
}
}
/**
- * Constructs a tokenizer splitting on the specified character.
+ * Constructs a tokenizer splitting on the specified delimiter character.
*
- * @param input the string which is to be parsed, not cloned
- * @param delim the field delimiter character
+ * @param input the string which is to be parsed
+ * @param delim the field delimiter character
*/
- public StrTokenizer(final char[] input, final char delim) {
+ public StrTokenizer(final String input, final char delim) {
this(input);
setDelimiterChar(delim);
}
/**
- * Constructs a tokenizer splitting on the specified string.
+ * Constructs a tokenizer splitting on the specified delimiter character
+ * and handling quotes using the specified quote character.
*
- * @param input the string which is to be parsed, not cloned
- * @param delim the field delimiter string
+ * @param input the string which is to be parsed
+ * @param delim the field delimiter character
+ * @param quote the field quoted string character
*/
- public StrTokenizer(final char[] input, final String delim) {
- this(input);
- setDelimiterString(delim);
+ public StrTokenizer(final String input, final char delim, final char quote) {
+ this(input, delim);
+ setQuoteChar(quote);
}
/**
- * Constructs a tokenizer splitting using the specified delimiter matcher.
+ * Constructs a tokenizer splitting on the specified delimiter string.
*
- * @param input the string which is to be parsed, not cloned
- * @param delim the field delimiter matcher
+ * @param input the string which is to be parsed
+ * @param delim the field delimiter string
*/
- public StrTokenizer(final char[] input, final StrMatcher delim) {
+ public StrTokenizer(final String input, final String delim) {
this(input);
- setDelimiterMatcher(delim);
+ setDelimiterString(delim);
}
/**
- * Constructs a tokenizer splitting on the specified delimiter character
- * and handling quotes using the specified quote character.
+ * Constructs a tokenizer splitting using the specified delimiter matcher.
*
- * @param input the string which is to be parsed, not cloned
- * @param delim the field delimiter character
- * @param quote the field quoted string character
+ * @param input the string which is to be parsed
+ * @param delim the field delimiter matcher
*/
- public StrTokenizer(final char[] input, final char delim, final char quote) {
- this(input, delim);
- setQuoteChar(quote);
+ public StrTokenizer(final String input, final StrMatcher delim) {
+ this(input);
+ setDelimiterMatcher(delim);
}
/**
* Constructs a tokenizer splitting using the specified delimiter matcher
* and handling quotes using the specified quote matcher.
*
- * @param input the string which is to be parsed, not cloned
- * @param delim the field delimiter character
- * @param quote the field quoted string character
+ * @param input the string which is to be parsed
+ * @param delim the field delimiter matcher
+ * @param quote the field quoted string matcher
*/
- public StrTokenizer(final char[] input, final StrMatcher delim, final StrMatcher quote) {
+ public StrTokenizer(final String input, final StrMatcher delim, final StrMatcher quote) {
this(input, delim);
setQuoteMatcher(quote);
}
- // API
- //-----------------------------------------------------------------------
/**
- * Gets the number of tokens found in the String.
- *
- * @return The number of matched tokens
+ * Unsupported ListIterator operation.
+ * @param obj this parameter ignored.
+ * @throws UnsupportedOperationException always
*/
- public int size() {
- checkTokenized();
- return tokens.length;
+ @Override
+ public void add(final String obj) {
+ throw new UnsupportedOperationException("add() is unsupported");
}
/**
- * Gets the next token from the String.
- * Equivalent to {@link #next()} except it returns null rather than
- * throwing {@link NoSuchElementException} when no tokens remain.
+ * Adds a token to a list, paying attention to the parameters we've set.
*
- * @return The next sequential token, or null when no more tokens are found
+ * @param list the list to add to
+ * @param tok the token to add
*/
- public String nextToken() {
- if (hasNext()) {
- return tokens[tokenPos++];
+ private void addToken(final List<String> list, String tok) {
+ if (tok == null || tok.isEmpty()) {
+ if (isIgnoreEmptyTokens()) {
+ return;
+ }
+ if (isEmptyTokenAsNull()) {
+ tok = null;
+ }
}
- return null;
+ list.add(tok);
}
+ // Implementation
+ //-----------------------------------------------------------------------
/**
- * Gets the previous token from the String.
- *
- * @return The previous sequential token, or null when no more tokens are found
+ * Checks if tokenization has been done, and if not then do it.
*/
- public String previousToken() {
- if (hasPrevious()) {
- return tokens[--tokenPos];
+ private void checkTokenized() {
+ if (tokens == null) {
+ if (chars == null) {
+ // still call tokenize as subclass may do some work
+ final List<String> split = tokenize(null, 0, 0);
+ tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
+ } else {
+ final List<String> split = tokenize(chars, 0, chars.length);
+ tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
+ }
}
- return null;
}
+ //-----------------------------------------------------------------------
/**
- * Gets a copy of the full token list as an independent modifiable array.
+ * Creates a new instance of this Tokenizer. The new instance is reset so
+ * that it will be at the start of the token list.
+ * If a {@link CloneNotSupportedException} is caught, return {@code null}.
*
- * @return The tokens as a String array
+ * @return a new instance of this Tokenizer which has been reset.
*/
- public String[] getTokenArray() {
+ @Override
+ public Object clone() {
+ try {
+ return cloneReset();
+ } catch (final CloneNotSupportedException ex) {
+ return null;
+ }
+ }
+
+ /**
+ * Creates a new instance of this Tokenizer. The new instance is reset so that
+ * it will be at the start of the token list.
+ *
+ * @return a new instance of this Tokenizer which has been reset.
+ * @throws CloneNotSupportedException if there is a problem cloning
+ */
+ Object cloneReset() throws CloneNotSupportedException {
+ // this method exists to enable 100% test coverage
+ final StrTokenizer cloned = (StrTokenizer) super.clone();
+ if (cloned.chars != null) {
+ cloned.chars = cloned.chars.clone();
+ }
+ cloned.reset();
+ return cloned;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the String content that the tokenizer is parsing.
+ *
+ * @return The string content being parsed
+ */
+ public String getContent() {
+ if (chars == null) {
+ return null;
+ }
+ return new String(chars);
+ }
+
+ // Delimiter
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the field delimiter matcher.
+ *
+ * @return The delimiter matcher in use
+ */
+ public StrMatcher getDelimiterMatcher() {
+ return this.delimMatcher;
+ }
+
+ // Ignored
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the ignored character matcher.
+ * <p>
+ * These characters are ignored when parsing the String, unless they are
+ * within a quoted region.
+ * The default value is not to ignore anything.
+ *
+ * @return The ignored matcher in use
+ */
+ public StrMatcher getIgnoredMatcher() {
+ return ignoredMatcher;
+ }
+
+ // Quote
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the quote matcher currently in use.
+ * <p>
+ * The quote character is used to wrap data between the tokens.
+ * This enables delimiters to be entered as data.
+ * The default value is '"' (double quote).
+ *
+ * @return The quote matcher in use
+ */
+ public StrMatcher getQuoteMatcher() {
+ return quoteMatcher;
+ }
+
+ /**
+ * Gets a copy of the full token list as an independent modifiable array.
+ *
+ * @return The tokens as a String array
+ */
+ public String[] getTokenArray() {
checkTokenized();
return tokens.clone();
}
@@ -449,66 +545,89 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
return list;
}
+ // Trimmer
+ //-----------------------------------------------------------------------
/**
- * Resets this tokenizer, forgetting all parsing and iteration already completed.
+ * Gets the trimmer character matcher.
* <p>
- * This method allows the same tokenizer to be reused for the same String.
+ * These characters are trimmed off on each side of the delimiter
+ * until the token or quote is found.
+ * The default value is not to trim anything.
*
- * @return this, to enable chaining
+ * @return The trimmer matcher in use
*/
- public StrTokenizer reset() {
- tokenPos = 0;
- tokens = null;
- return this;
+ public StrMatcher getTrimmerMatcher() {
+ return trimmerMatcher;
}
+ // ListIterator
+ //-----------------------------------------------------------------------
/**
- * Reset this tokenizer, giving it a new input string to parse.
- * In this manner you can re-use a tokenizer with the same settings
- * on multiple input lines.
+ * Checks whether there are any more tokens.
*
- * @param input the new string to tokenize, null sets no text to parse
- * @return this, to enable chaining
+ * @return true if there are more tokens
*/
- public StrTokenizer reset(final String input) {
- reset();
- if (input != null) {
- this.chars = input.toCharArray();
- } else {
- this.chars = null;
- }
- return this;
+ @Override
+ public boolean hasNext() {
+ checkTokenized();
+ return tokenPos < tokens.length;
}
/**
- * Reset this tokenizer, giving it a new input string to parse.
- * In this manner you can re-use a tokenizer with the same settings
- * on multiple input lines.
+ * Checks whether there are any previous tokens that can be iterated to.
*
- * @param input the new character array to tokenize, not cloned, null sets no text to parse
- * @return this, to enable chaining
+ * @return true if there are previous tokens
*/
- public StrTokenizer reset(final char[] input) {
- reset();
- if (input != null) {
- this.chars = input.clone();
- } else {
- this.chars = null;
- }
- return this;
+ @Override
+ public boolean hasPrevious() {
+ checkTokenized();
+ return tokenPos > 0;
}
- // ListIterator
//-----------------------------------------------------------------------
/**
- * Checks whether there are any more tokens.
+ * Gets whether the tokenizer currently returns empty tokens as null.
+ * The default for this property is false.
*
- * @return true if there are more tokens
+ * @return true if empty tokens are returned as null
*/
- @Override
- public boolean hasNext() {
- checkTokenized();
- return tokenPos < tokens.length;
+ public boolean isEmptyTokenAsNull() {
+ return this.emptyAsNull;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets whether the tokenizer currently ignores empty tokens.
+ * The default for this property is true.
+ *
+ * @return true if empty tokens are not returned
+ */
+ public boolean isIgnoreEmptyTokens() {
+ return ignoreEmptyTokens;
+ }
+
+ /**
+ * Checks if the characters at the index specified match the quote
+ * already matched in readNextToken().
+ *
+ * @param srcChars the character array being tokenized
+ * @param pos the position to check for a quote
+ * @param len the length of the character array being tokenized
+ * @param quoteStart the start position of the matched quote, 0 if no quoting
+ * @param quoteLen the length of the matched quote, 0 if no quoting
+ * @return true if a quote is matched
+ */
+ private boolean isQuote(final char[] srcChars,
+ final int pos,
+ final int len,
+ final int quoteStart,
+ final int quoteLen) {
+ for (int i = 0; i < quoteLen; i++) {
+ if (pos + i >= len || srcChars[pos + i] != srcChars[quoteStart + i]) {
+ return false;
+ }
+ }
+ return true;
}
/**
@@ -536,14 +655,17 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
}
/**
- * Checks whether there are any previous tokens that can be iterated to.
+ * Gets the next token from the String.
+ * Equivalent to {@link #next()} except it returns null rather than
+ * throwing {@link NoSuchElementException} when no tokens remain.
*
- * @return true if there are previous tokens
+ * @return The next sequential token, or null when no more tokens are found
*/
- @Override
- public boolean hasPrevious() {
- checkTokenized();
- return tokenPos > 0;
+ public String nextToken() {
+ if (hasNext()) {
+ return tokens[tokenPos++];
+ }
+ return null;
}
/**
@@ -570,110 +692,15 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
}
/**
- * Unsupported ListIterator operation.
- *
- * @throws UnsupportedOperationException always
- */
- @Override
- public void remove() {
- throw new UnsupportedOperationException("remove() is unsupported");
- }
-
- /**
- * Unsupported ListIterator operation.
- * @param obj this parameter ignored.
- * @throws UnsupportedOperationException always
- */
- @Override
- public void set(final String obj) {
- throw new UnsupportedOperationException("set() is unsupported");
- }
-
- /**
- * Unsupported ListIterator operation.
- * @param obj this parameter ignored.
- * @throws UnsupportedOperationException always
- */
- @Override
- public void add(final String obj) {
- throw new UnsupportedOperationException("add() is unsupported");
- }
-
- // Implementation
- //-----------------------------------------------------------------------
- /**
- * Checks if tokenization has been done, and if not then do it.
- */
- private void checkTokenized() {
- if (tokens == null) {
- if (chars == null) {
- // still call tokenize as subclass may do some work
- final List<String> split = tokenize(null, 0, 0);
- tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
- } else {
- final List<String> split = tokenize(chars, 0, chars.length);
- tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
- }
- }
- }
-
- /**
- * Internal method to performs the tokenization.
- * <p>
- * Most users of this class do not need to call this method. This method
- * will be called automatically by other (public) methods when required.
- * <p>
- * This method exists to allow subclasses to add code before or after the
- * tokenization. For example, a subclass could alter the character array,
- * offset or count to be parsed, or call the tokenizer multiple times on
- * multiple strings. It is also be possible to filter the results.
- * <p>
- * {@code StrTokenizer} will always pass a zero offset and a count
- * equal to the length of the array to this method, however a subclass
- * may pass other values, or even an entirely different array.
- *
- * @param srcChars the character array being tokenized, may be null
- * @param offset the start position within the character array, must be valid
- * @param count the number of characters to tokenize, must be valid
- * @return The modifiable list of String tokens, unmodifiable if null array or zero count
- */
- protected List<String> tokenize(final char[] srcChars, final int offset, final int count) {
- if (srcChars == null || count == 0) {
- return Collections.emptyList();
- }
- final StrBuilder buf = new StrBuilder();
- final List<String> tokenList = new ArrayList<>();
- int pos = offset;
-
- // loop around the entire buffer
- while (pos >= 0 && pos < count) {
- // find next token
- pos = readNextToken(srcChars, pos, count, buf, tokenList);
-
- // handle case where end of string is a delimiter
- if (pos >= count) {
- addToken(tokenList, StringUtils.EMPTY);
- }
- }
- return tokenList;
- }
-
- /**
- * Adds a token to a list, paying attention to the parameters we've set.
+ * Gets the previous token from the String.
*
- * @param list the list to add to
- * @param tok the token to add
+ * @return The previous sequential token, or null when no more tokens are found
*/
- private void addToken(final List<String> list, String tok) {
- if (tok == null || tok.isEmpty()) {
- if (isIgnoreEmptyTokens()) {
- return;
- }
- if (isEmptyTokenAsNull()) {
- tok = null;
- }
+ public String previousToken() {
+ if (hasPrevious()) {
+ return tokens[--tokenPos];
}
- list.add(tok);
+ return null;
}
/**
@@ -827,38 +854,82 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
}
/**
- * Checks if the characters at the index specified match the quote
- * already matched in readNextToken().
+ * Unsupported ListIterator operation.
*
- * @param srcChars the character array being tokenized
- * @param pos the position to check for a quote
- * @param len the length of the character array being tokenized
- * @param quoteStart the start position of the matched quote, 0 if no quoting
- * @param quoteLen the length of the matched quote, 0 if no quoting
- * @return true if a quote is matched
+ * @throws UnsupportedOperationException always
*/
- private boolean isQuote(final char[] srcChars,
- final int pos,
- final int len,
- final int quoteStart,
- final int quoteLen) {
- for (int i = 0; i < quoteLen; i++) {
- if (pos + i >= len || srcChars[pos + i] != srcChars[quoteStart + i]) {
- return false;
- }
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException("remove() is unsupported");
+ }
+
+ /**
+ * Resets this tokenizer, forgetting all parsing and iteration already completed.
+ * <p>
+ * This method allows the same tokenizer to be reused for the same String.
+ *
+ * @return this, to enable chaining
+ */
+ public StrTokenizer reset() {
+ tokenPos = 0;
+ tokens = null;
+ return this;
+ }
+
+ /**
+ * Reset this tokenizer, giving it a new input string to parse.
+ * In this manner you can re-use a tokenizer with the same settings
+ * on multiple input lines.
+ *
+ * @param input the new character array to tokenize, not cloned, null sets no text to parse
+ * @return this, to enable chaining
+ */
+ public StrTokenizer reset(final char[] input) {
+ reset();
+ if (input != null) {
+ this.chars = input.clone();
+ } else {
+ this.chars = null;
+ }
+ return this;
+ }
+
+ /**
+ * Reset this tokenizer, giving it a new input string to parse.
+ * In this manner you can re-use a tokenizer with the same settings
+ * on multiple input lines.
+ *
+ * @param input the new string to tokenize, null sets no text to parse
+ * @return this, to enable chaining
+ */
+ public StrTokenizer reset(final String input) {
+ reset();
+ if (input != null) {
+ this.chars = input.toCharArray();
+ } else {
+ this.chars = null;
}
- return true;
+ return this;
}
- // Delimiter
- //-----------------------------------------------------------------------
/**
- * Gets the field delimiter matcher.
+ * Unsupported ListIterator operation.
+ * @param obj this parameter ignored.
+ * @throws UnsupportedOperationException always
+ */
+ @Override
+ public void set(final String obj) {
+ throw new UnsupportedOperationException("set() is unsupported");
+ }
+
+ /**
+ * Sets the field delimiter character.
*
- * @return The delimiter matcher in use
+ * @param delim the delimiter character to use
+ * @return this, to enable chaining
*/
- public StrMatcher getDelimiterMatcher() {
- return this.delimMatcher;
+ public StrTokenizer setDelimiterChar(final char delim) {
+ return setDelimiterMatcher(StrMatcher.charMatcher(delim));
}
/**
@@ -879,16 +950,6 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
}
/**
- * Sets the field delimiter character.
- *
- * @param delim the delimiter character to use
- * @return this, to enable chaining
- */
- public StrTokenizer setDelimiterChar(final char delim) {
- return setDelimiterMatcher(StrMatcher.charMatcher(delim));
- }
-
- /**
* Sets the field delimiter string.
*
* @param delim the delimiter string to use
@@ -898,63 +959,29 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
return setDelimiterMatcher(StrMatcher.stringMatcher(delim));
}
- // Quote
- //-----------------------------------------------------------------------
- /**
- * Gets the quote matcher currently in use.
- * <p>
- * The quote character is used to wrap data between the tokens.
- * This enables delimiters to be entered as data.
- * The default value is '"' (double quote).
- *
- * @return The quote matcher in use
- */
- public StrMatcher getQuoteMatcher() {
- return quoteMatcher;
- }
-
/**
- * Set the quote matcher to use.
- * <p>
- * The quote character is used to wrap data between the tokens.
- * This enables delimiters to be entered as data.
+ * Sets whether the tokenizer should return empty tokens as null.
+ * The default for this property is false.
*
- * @param quote the quote matcher to use, null ignored
+ * @param emptyAsNull whether empty tokens are returned as null
* @return this, to enable chaining
*/
- public StrTokenizer setQuoteMatcher(final StrMatcher quote) {
- if (quote != null) {
- this.quoteMatcher = quote;
- }
+ public StrTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) {
+ this.emptyAsNull = emptyAsNull;
return this;
}
/**
- * Sets the quote character to use.
- * <p>
- * The quote character is used to wrap data between the tokens.
- * This enables delimiters to be entered as data.
- *
- * @param quote the quote character to use
- * @return this, to enable chaining
- */
- public StrTokenizer setQuoteChar(final char quote) {
- return setQuoteMatcher(StrMatcher.charMatcher(quote));
- }
-
- // Ignored
- //-----------------------------------------------------------------------
- /**
- * Gets the ignored character matcher.
+ * Set the character to ignore.
* <p>
- * These characters are ignored when parsing the String, unless they are
+ * This character is ignored when parsing the String, unless it is
* within a quoted region.
- * The default value is not to ignore anything.
*
- * @return The ignored matcher in use
+ * @param ignored the ignored character to use
+ * @return this, to enable chaining
*/
- public StrMatcher getIgnoredMatcher() {
- return ignoredMatcher;
+ public StrTokenizer setIgnoredChar(final char ignored) {
+ return setIgnoredMatcher(StrMatcher.charMatcher(ignored));
}
/**
@@ -974,31 +1001,44 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
}
/**
- * Set the character to ignore.
+ * Sets whether the tokenizer should ignore and not return empty tokens.
+ * The default for this property is true.
+ *
+ * @param ignoreEmptyTokens whether empty tokens are not returned
+ * @return this, to enable chaining
+ */
+ public StrTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) {
+ this.ignoreEmptyTokens = ignoreEmptyTokens;
+ return this;
+ }
+
+ /**
+ * Sets the quote character to use.
* <p>
- * This character is ignored when parsing the String, unless it is
- * within a quoted region.
+ * The quote character is used to wrap data between the tokens.
+ * This enables delimiters to be entered as data.
*
- * @param ignored the ignored character to use
+ * @param quote the quote character to use
* @return this, to enable chaining
*/
- public StrTokenizer setIgnoredChar(final char ignored) {
- return setIgnoredMatcher(StrMatcher.charMatcher(ignored));
+ public StrTokenizer setQuoteChar(final char quote) {
+ return setQuoteMatcher(StrMatcher.charMatcher(quote));
}
- // Trimmer
- //-----------------------------------------------------------------------
/**
- * Gets the trimmer character matcher.
+ * Set the quote matcher to use.
* <p>
- * These characters are trimmed off on each side of the delimiter
- * until the token or quote is found.
- * The default value is not to trim anything.
+ * The quote character is used to wrap data between the tokens.
+ * This enables delimiters to be entered as data.
*
- * @return The trimmer matcher in use
+ * @param quote the quote matcher to use, null ignored
+ * @return this, to enable chaining
*/
- public StrMatcher getTrimmerMatcher() {
- return trimmerMatcher;
+ public StrTokenizer setQuoteMatcher(final StrMatcher quote) {
+ if (quote != null) {
+ this.quoteMatcher = quote;
+ }
+ return this;
}
/**
@@ -1017,97 +1057,57 @@ public class StrTokenizer implements ListIterator<String>, Cloneable {
return this;
}
+ // API
//-----------------------------------------------------------------------
/**
- * Gets whether the tokenizer currently returns empty tokens as null.
- * The default for this property is false.
- *
- * @return true if empty tokens are returned as null
- */
- public boolean isEmptyTokenAsNull() {
- return this.emptyAsNull;
- }
-
- /**
- * Sets whether the tokenizer should return empty tokens as null.
- * The default for this property is false.
- *
- * @param emptyAsNull whether empty tokens are returned as null
- * @return this, to enable chaining
- */
- public StrTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) {
- this.emptyAsNull = emptyAsNull;
- return this;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Gets whether the tokenizer currently ignores empty tokens.
- * The default for this property is true.
- *
- * @return true if empty tokens are not returned
- */
- public boolean isIgnoreEmptyTokens() {
- return ignoreEmptyTokens;
- }
-
- /**
- * Sets whether the tokenizer should ignore and not return empty tokens.
- * The default for this property is true.
+ * Gets the number of tokens found in the String.
*
- * @param ignoreEmptyTokens whether empty tokens are not returned
- * @return this, to enable chaining
+ * @return The number of matched tokens
*/
- public StrTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) {
- this.ignoreEmptyTokens = ignoreEmptyTokens;
- return this;
+ public int size() {
+ checkTokenized();
+ return tokens.length;
}
- //-----------------------------------------------------------------------
/**
- * Gets the String content that the tokenizer is parsing.
+ * Internal method to performs the tokenization.
+ * <p>
+ * Most users of this class do not need to call this method. This method
+ * will be called automatically by other (public) methods when required.
+ * <p>
+ * This method exists to allow subclasses to add code before or after the
+ * tokenization. For example, a subclass could alter the character array,
+ * offset or count to be parsed, or call the tokenizer multiple times on
+ * multiple strings. It is also be possible to filter the results.
+ * <p>
+ * {@code StrTokenizer} will always pass a zero offset and a count
+ * equal to the length of the array to this method, however a subclass
+ * may pass other values, or even an entirely different array.
*
- * @return The string content being parsed
+ * @param srcChars the character array being tokenized, may be null
+ * @param offset the start position within the character array, must be valid
+ * @param count the number of characters to tokenize, must be valid
+ * @return The modifiable list of String tokens, unmodifiable if null array or zero count
*/
- public String getContent() {
- if (chars == null) {
- return null;
+ protected List<String> tokenize(final char[] srcChars, final int offset, final int count) {
+ if (srcChars == null || count == 0) {
+ return Collections.emptyList();
}
- return new String(chars);
- }
+ final StrBuilder buf = new StrBuilder();
+ final List<String> tokenList = new ArrayList<>();
+ int pos = offset;
- //-----------------------------------------------------------------------
- /**
- * Creates a new instance of this Tokenizer. The new instance is reset so
- * that it will be at the start of the token list.
- * If a {@link CloneNotSupportedException} is caught, return {@code null}.
- *
- * @return a new instance of this Tokenizer which has been reset.
- */
- @Override
- public Object clone() {
- try {
- return cloneReset();
- } catch (final CloneNotSupportedException ex) {
- return null;
- }
- }
+ // loop around the entire buffer
+ while (pos >= 0 && pos < count) {
+ // find next token
+ pos = readNextToken(srcChars, pos, count, buf, tokenList);
- /**
- * Creates a new instance of this Tokenizer. The new instance is reset so that
- * it will be at the start of the token list.
- *
- * @return a new instance of this Tokenizer which has been reset.
- * @throws CloneNotSupportedException if there is a problem cloning
- */
- Object cloneReset() throws CloneNotSupportedException {
- // this method exists to enable 100% test coverage
- final StrTokenizer cloned = (StrTokenizer) super.clone();
- if (cloned.chars != null) {
- cloned.chars = cloned.chars.clone();
+ // handle case where end of string is a delimiter
+ if (pos >= count) {
+ addToken(tokenList, StringUtils.EMPTY);
+ }
}
- cloned.reset();
- return cloned;
+ return tokenList;
}
//-----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/text/StringTokenizer.java b/src/main/java/org/apache/commons/text/StringTokenizer.java
index 654f8a6..9cd9922 100644
--- a/src/main/java/org/apache/commons/text/StringTokenizer.java
+++ b/src/main/java/org/apache/commons/text/StringTokenizer.java
@@ -115,27 +115,6 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
TSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);
}
- /** The text to work on. */
- private char[] chars;
- /** The parsed tokens. */
- private String[] tokens;
- /** The current iteration position. */
- private int tokenPos;
-
- /** The delimiter matcher. */
- private StringMatcher delimMatcher = StringMatcherFactory.INSTANCE.splitMatcher();
- /** The quote matcher. */
- private StringMatcher quoteMatcher = StringMatcherFactory.INSTANCE.noneMatcher();
- /** The ignored matcher. */
- private StringMatcher ignoredMatcher = StringMatcherFactory.INSTANCE.noneMatcher();
- /** The trimmer matcher. */
- private StringMatcher trimmerMatcher = StringMatcherFactory.INSTANCE.noneMatcher();
-
- /** Whether to return empty tokens as null. */
- private boolean emptyAsNull;
- /** Whether to ignore empty tokens. */
- private boolean ignoreEmptyTokens = true;
-
/**
* Returns a clone of {@code CSV_TOKENIZER_PROTOTYPE}.
*
@@ -144,7 +123,6 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
private static StringTokenizer getCSVClone() {
return (StringTokenizer) CSV_TOKENIZER_PROTOTYPE.clone();
}
-
/**
* Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input.
* The default for CSV processing will be trim whitespace from both ends (which can be overridden with the
@@ -158,7 +136,6 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
public static StringTokenizer getCSVInstance() {
return getCSVClone();
}
-
/**
* Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input.
* The default for CSV processing will be trim whitespace from both ends (which can be overridden with the
@@ -168,7 +145,7 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
* the text to parse
* @return a new tokenizer instance which parses Comma Separated Value strings
*/
- public static StringTokenizer getCSVInstance(final String input) {
+ public static StringTokenizer getCSVInstance(final char[] input) {
return getCSVClone().reset(input);
}
@@ -181,10 +158,9 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
* the text to parse
* @return a new tokenizer instance which parses Comma Separated Value strings
*/
- public static StringTokenizer getCSVInstance(final char[] input) {
+ public static StringTokenizer getCSVInstance(final String input) {
return getCSVClone().reset(input);
}
-
/**
* Returns a clone of {@code TSV_TOKENIZER_PROTOTYPE}.
*
@@ -193,7 +169,6 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
private static StringTokenizer getTSVClone() {
return (StringTokenizer) TSV_TOKENIZER_PROTOTYPE.clone();
}
-
/**
* Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be
* trim whitespace from both ends (which can be overridden with the setTrimmer method).
@@ -206,7 +181,6 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
public static StringTokenizer getTSVInstance() {
return getTSVClone();
}
-
/**
* Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be
* trim whitespace from both ends (which can be overridden with the setTrimmer method).
@@ -215,7 +189,7 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
* the string to parse
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
- public static StringTokenizer getTSVInstance(final String input) {
+ public static StringTokenizer getTSVInstance(final char[] input) {
return getTSVClone().reset(input);
}
@@ -227,9 +201,35 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
* the string to parse
* @return a new tokenizer instance which parses Tab Separated Value strings.
*/
- public static StringTokenizer getTSVInstance(final char[] input) {
+ public static StringTokenizer getTSVInstance(final String input) {
return getTSVClone().reset(input);
}
+ /** The text to work on. */
+ private char[] chars;
+
+ /** The parsed tokens. */
+ private String[] tokens;
+
+ /** The current iteration position. */
+ private int tokenPos;
+
+ /** The delimiter matcher. */
+ private StringMatcher delimMatcher = StringMatcherFactory.INSTANCE.splitMatcher();
+
+ /** The quote matcher. */
+ private StringMatcher quoteMatcher = StringMatcherFactory.INSTANCE.noneMatcher();
+
+ /** The ignored matcher. */
+ private StringMatcher ignoredMatcher = StringMatcherFactory.INSTANCE.noneMatcher();
+
+ /** The trimmer matcher. */
+ private StringMatcher trimmerMatcher = StringMatcherFactory.INSTANCE.noneMatcher();
+
+ /** Whether to return empty tokens as null. */
+ private boolean emptyAsNull;
+
+ /** Whether to ignore empty tokens. */
+ private boolean ignoreEmptyTokens = true;
/**
* Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer, but with no text to
@@ -246,34 +246,50 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
* Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer.
*
* @param input
- * the string which is to be parsed
+ * the string which is to be parsed, not cloned
*/
- public StringTokenizer(final String input) {
- this.chars = input != null ? input.toCharArray() : null;
+ public StringTokenizer(final char[] input) {
+ this.chars = input != null ? input.clone() : null;
}
/**
- * Constructs a tokenizer splitting on the specified delimiter character.
+ * Constructs a tokenizer splitting on the specified character.
*
* @param input
- * the string which is to be parsed
+ * the string which is to be parsed, not cloned
* @param delim
* the field delimiter character
*/
- public StringTokenizer(final String input, final char delim) {
+ public StringTokenizer(final char[] input, final char delim) {
this(input);
setDelimiterChar(delim);
}
/**
- * Constructs a tokenizer splitting on the specified delimiter string.
+ * Constructs a tokenizer splitting on the specified delimiter character and handling quotes using the specified
+ * quote character.
*
* @param input
- * the string which is to be parsed
+ * the string which is to be parsed, not cloned
+ * @param delim
+ * the field delimiter character
+ * @param quote
+ * the field quoted string character
+ */
+ public StringTokenizer(final char[] input, final char delim, final char quote) {
+ this(input, delim);
+ setQuoteChar(quote);
+ }
+
+ /**
+ * Constructs a tokenizer splitting on the specified string.
+ *
+ * @param input
+ * the string which is to be parsed, not cloned
* @param delim
* the field delimiter string
*/
- public StringTokenizer(final String input, final String delim) {
+ public StringTokenizer(final char[] input, final String delim) {
this(input);
setDelimiterString(delim);
}
@@ -282,79 +298,79 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
* Constructs a tokenizer splitting using the specified delimiter matcher.
*
* @param input
- * the string which is to be parsed
+ * the string which is to be parsed, not cloned
* @param delim
* the field delimiter matcher
*/
- public StringTokenizer(final String input, final StringMatcher delim) {
+ public StringTokenizer(final char[] input, final StringMatcher delim) {
this(input);
setDelimiterMatcher(delim);
}
/**
- * Constructs a tokenizer splitting on the specified delimiter character and handling quotes using the specified
- * quote character.
+ * Constructs a tokenizer splitting using the specified delimiter matcher and handling quotes using the specified
+ * quote matcher.
*
* @param input
- * the string which is to be parsed
+ * the string which is to be parsed, not cloned
* @param delim
* the field delimiter character
* @param quote
* the field quoted string character
*/
- public StringTokenizer(final String input, final char delim, final char quote) {
+ public StringTokenizer(final char[] input, final StringMatcher delim, final StringMatcher quote) {
this(input, delim);
- setQuoteChar(quote);
+ setQuoteMatcher(quote);
}
/**
- * Constructs a tokenizer splitting using the specified delimiter matcher and handling quotes using the specified
- * quote matcher.
+ * Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer.
*
* @param input
* the string which is to be parsed
- * @param delim
- * the field delimiter matcher
- * @param quote
- * the field quoted string matcher
*/
- public StringTokenizer(final String input, final StringMatcher delim, final StringMatcher quote) {
- this(input, delim);
- setQuoteMatcher(quote);
+ public StringTokenizer(final String input) {
+ this.chars = input != null ? input.toCharArray() : null;
}
/**
- * Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer.
+ * Constructs a tokenizer splitting on the specified delimiter character.
*
* @param input
- * the string which is to be parsed, not cloned
+ * the string which is to be parsed
+ * @param delim
+ * the field delimiter character
*/
- public StringTokenizer(final char[] input) {
- this.chars = input != null ? input.clone() : null;
+ public StringTokenizer(final String input, final char delim) {
+ this(input);
+ setDelimiterChar(delim);
}
/**
- * Constructs a tokenizer splitting on the specified character.
+ * Constructs a tokenizer splitting on the specified delimiter character and handling quotes using the specified
+ * quote character.
*
* @param input
- * the string which is to be parsed, not cloned
+ * the string which is to be parsed
* @param delim
* the field delimiter character
+ * @param quote
+ * the field quoted string character
*/
- public StringTokenizer(final char[] input, final char delim) {
- this(input);
- setDelimiterChar(delim);
+ public StringTokenizer(final String input, final char delim, final char quote) {
+ this(input, delim);
+ setQuoteChar(quote);
}
/**
- * Constructs a tokenizer splitting on the specified string.
+ * Constructs a tokenizer splitting on the specified delimiter string.
*
* @param input
- * the string which is to be parsed, not cloned
+ * the string which is to be parsed
* @param delim
* the field delimiter string
*/
- public StringTokenizer(final char[] input, final String delim) {
+ public StringTokenizer(final String input, final String delim) {
this(input);
setDelimiterString(delim);
}
@@ -363,177 +379,202 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
* Constructs a tokenizer splitting using the specified delimiter matcher.
*
* @param input
- * the string which is to be parsed, not cloned
+ * the string which is to be parsed
* @param delim
* the field delimiter matcher
*/
- public StringTokenizer(final char[] input, final StringMatcher delim) {
+ public StringTokenizer(final String input, final StringMatcher delim) {
this(input);
setDelimiterMatcher(delim);
}
/**
- * Constructs a tokenizer splitting on the specified delimiter character and handling quotes using the specified
- * quote character.
- *
- * @param input
- * the string which is to be parsed, not cloned
- * @param delim
- * the field delimiter character
- * @param quote
- * the field quoted string character
- */
- public StringTokenizer(final char[] input, final char delim, final char quote) {
- this(input, delim);
- setQuoteChar(quote);
- }
-
- /**
* Constructs a tokenizer splitting using the specified delimiter matcher and handling quotes using the specified
* quote matcher.
*
* @param input
- * the string which is to be parsed, not cloned
+ * the string which is to be parsed
* @param delim
- * the field delimiter character
+ * the field delimiter matcher
* @param quote
- * the field quoted string character
+ * the field quoted string matcher
*/
- public StringTokenizer(final char[] input, final StringMatcher delim, final StringMatcher quote) {
+ public StringTokenizer(final String input, final StringMatcher delim, final StringMatcher quote) {
this(input, delim);
setQuoteMatcher(quote);
}
/**
- * Gets the number of tokens found in the String.
+ * Unsupported ListIterator operation.
*
- * @return The number of matched tokens
+ * @param obj
+ * this parameter ignored.
+ * @throws UnsupportedOperationException
+ * always
*/
- public int size() {
- checkTokenized();
- return tokens.length;
+ @Override
+ public void add(final String obj) {
+ throw new UnsupportedOperationException("add() is unsupported");
}
/**
- * Gets the next token from the String. Equivalent to {@link #next()} except it returns null rather than throwing
- * {@link NoSuchElementException} when no tokens remain.
+ * Adds a token to a list, paying attention to the parameters we've set.
*
- * @return The next sequential token, or null when no more tokens are found
+ * @param list
+ * the list to add to
+ * @param tok
+ * the token to add
*/
- public String nextToken() {
- if (hasNext()) {
- return tokens[tokenPos++];
+ private void addToken(final List<String> list, String tok) {
+ if (tok == null || tok.isEmpty()) {
+ if (isIgnoreEmptyTokens()) {
+ return;
+ }
+ if (isEmptyTokenAsNull()) {
+ tok = null;
+ }
}
- return null;
+ list.add(tok);
}
/**
- * Gets the previous token from the String.
- *
- * @return The previous sequential token, or null when no more tokens are found
+ * Checks if tokenization has been done, and if not then do it.
*/
- public String previousToken() {
- if (hasPrevious()) {
- return tokens[--tokenPos];
+ private void checkTokenized() {
+ if (tokens == null) {
+ final List<String> split;
+ if (chars == null) {
+ // still call tokenize as subclass may do some work
+ split = tokenize(null, 0, 0);
+ } else {
+ split = tokenize(chars, 0, chars.length);
+ }
+ tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
- return null;
}
/**
- * Gets a copy of the full token list as an independent modifiable array.
+ * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token
+ * list. If a {@link CloneNotSupportedException} is caught, return {@code null}.
*
- * @return The tokens as a String array
+ * @return a new instance of this Tokenizer which has been reset.
*/
- public String[] getTokenArray() {
- checkTokenized();
- return tokens.clone();
+ @Override
+ public Object clone() {
+ try {
+ return cloneReset();
+ } catch (final CloneNotSupportedException ex) {
+ return null;
+ }
}
/**
- * Gets a copy of the full token list as an independent modifiable list.
+ * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token
+ * list.
*
- * @return The tokens as a String array
+ * @return a new instance of this Tokenizer which has been reset.
+ * @throws CloneNotSupportedException
+ * if there is a problem cloning
*/
- public List<String> getTokenList() {
- checkTokenized();
- return Arrays.asList(tokens);
- }
+ Object cloneReset() throws CloneNotSupportedException {
+ // this method exists to enable 100% test coverage
+ final StringTokenizer cloned = (StringTokenizer) super.clone();
+ if (cloned.chars != null) {
+ cloned.chars = cloned.chars.clone();
+ }
+ cloned.reset();
+ return cloned;
+ }
/**
- * Resets this tokenizer, forgetting all parsing and iteration already completed.
+ * Gets the String content that the tokenizer is parsing.
+ *
+ * @return The string content being parsed
+ */
+ public String getContent() {
+ if (chars == null) {
+ return null;
+ }
+ return new String(chars);
+ }
+
+ /**
+ * Gets the field delimiter matcher.
+ *
+ * @return The delimiter matcher in use
+ */
+ public StringMatcher getDelimiterMatcher() {
+ return this.delimMatcher;
+ }
+
+ /**
+ * Gets the ignored character matcher.
* <p>
- * This method allows the same tokenizer to be reused for the same String.
+ * These characters are ignored when parsing the String, unless they are within a quoted region. The default value
+ * is not to ignore anything.
+ * </p>
*
- * @return this, to enable chaining
+ * @return The ignored matcher in use
*/
- public StringTokenizer reset() {
- tokenPos = 0;
- tokens = null;
- return this;
+ public StringMatcher getIgnoredMatcher() {
+ return ignoredMatcher;
}
/**
- * Reset this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the
- * same settings on multiple input lines.
+ * Gets the quote matcher currently in use.
+ * <p>
+ * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data. The
+ * default value is '"' (double quote).
+ * </p>
*
- * @param input
- * the new string to tokenize, null sets no text to parse
- * @return this, to enable chaining
+ * @return The quote matcher in use
*/
- public StringTokenizer reset(final String input) {
- reset();
- this.chars = input != null ? input.toCharArray() : null;
- return this;
+ public StringMatcher getQuoteMatcher() {
+ return quoteMatcher;
}
/**
- * Reset this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the
- * same settings on multiple input lines.
+ * Gets a copy of the full token list as an independent modifiable array.
*
- * @param input
- * the new character array to tokenize, not cloned, null sets no text to parse
- * @return this, to enable chaining
+ * @return The tokens as a String array
*/
- public StringTokenizer reset(final char[] input) {
- reset();
- this.chars = input != null ? input.clone() : null;
- return this;
+ public String[] getTokenArray() {
+ checkTokenized();
+ return tokens.clone();
}
/**
- * Checks whether there are any more tokens.
+ * Gets a copy of the full token list as an independent modifiable list.
*
- * @return true if there are more tokens
+ * @return The tokens as a String array
*/
- @Override
- public boolean hasNext() {
+ public List<String> getTokenList() {
checkTokenized();
- return tokenPos < tokens.length;
+ return Arrays.asList(tokens);
}
/**
- * Gets the next token.
+ * Gets the trimmer character matcher.
+ * <p>
+ * These characters are trimmed off on each side of the delimiter until the token or quote is found. The default
+ * value is not to trim anything.
+ * </p>
*
- * @return The next String token
- * @throws NoSuchElementException
- * if there are no more elements
+ * @return The trimmer matcher in use
*/
- @Override
- public String next() {
- if (hasNext()) {
- return tokens[tokenPos++];
- }
- throw new NoSuchElementException();
+ public StringMatcher getTrimmerMatcher() {
+ return trimmerMatcher;
}
/**
- * Gets the index of the next token to return.
+ * Checks whether there are any more tokens.
*
- * @return The next token index
+ * @return true if there are more tokens
*/
@Override
- public int nextIndex() {
- return tokenPos;
+ public boolean hasNext() {
+ checkTokenized();
+ return tokenPos < tokens.length;
}
/**
@@ -548,144 +589,119 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
}
/**
- * Gets the token previous to the last returned token.
+ * Gets whether the tokenizer currently returns empty tokens as null. The default for this property is false.
*
- * @return The previous token
+ * @return true if empty tokens are returned as null
*/
- @Override
- public String previous() {
- if (hasPrevious()) {
- return tokens[--tokenPos];
- }
- throw new NoSuchElementException();
+ public boolean isEmptyTokenAsNull() {
+ return this.emptyAsNull;
}
/**
- * Gets the index of the previous token.
+ * Gets whether the tokenizer currently ignores empty tokens. The default for this property is true.
*
- * @return The previous token index
+ * @return true if empty tokens are not returned
*/
- @Override
- public int previousIndex() {
- return tokenPos - 1;
+ public boolean isIgnoreEmptyTokens() {
+ return ignoreEmptyTokens;
}
/**
- * Unsupported ListIterator operation.
+ * Checks if the characters at the index specified match the quote already matched in readNextToken().
*
- * @throws UnsupportedOperationException
- * always
+ * @param srcChars
+ * the character array being tokenized
+ * @param pos
+ * the position to check for a quote
+ * @param len
+ * the length of the character array being tokenized
+ * @param quoteStart
+ * the start position of the matched quote, 0 if no quoting
+ * @param quoteLen
+ * the length of the matched quote, 0 if no quoting
+ * @return true if a quote is matched
*/
- @Override
- public void remove() {
- throw new UnsupportedOperationException("remove() is unsupported");
+ private boolean isQuote(final char[] srcChars, final int pos, final int len, final int quoteStart,
+ final int quoteLen) {
+ for (int i = 0; i < quoteLen; i++) {
+ if (pos + i >= len || srcChars[pos + i] != srcChars[quoteStart + i]) {
+ return false;
+ }
+ }
+ return true;
}
/**
- * Unsupported ListIterator operation.
+ * Gets the next token.
*
- * @param obj
- * this parameter ignored.
- * @throws UnsupportedOperationException
- * always
+ * @return The next String token
+ * @throws NoSuchElementException
+ * if there are no more elements
*/
@Override
- public void set(final String obj) {
- throw new UnsupportedOperationException("set() is unsupported");
+ public String next() {
+ if (hasNext()) {
+ return tokens[tokenPos++];
+ }
+ throw new NoSuchElementException();
}
/**
- * Unsupported ListIterator operation.
+ * Gets the index of the next token to return.
*
- * @param obj
- * this parameter ignored.
- * @throws UnsupportedOperationException
- * always
+ * @return The next token index
*/
@Override
- public void add(final String obj) {
- throw new UnsupportedOperationException("add() is unsupported");
+ public int nextIndex() {
+ return tokenPos;
}
/**
- * Checks if tokenization has been done, and if not then do it.
+ * Gets the next token from the String. Equivalent to {@link #next()} except it returns null rather than throwing
+ * {@link NoSuchElementException} when no tokens remain.
+ *
+ * @return The next sequential token, or null when no more tokens are found
*/
- private void checkTokenized() {
- if (tokens == null) {
- final List<String> split;
- if (chars == null) {
- // still call tokenize as subclass may do some work
- split = tokenize(null, 0, 0);
- } else {
- split = tokenize(chars, 0, chars.length);
- }
- tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
+ public String nextToken() {
+ if (hasNext()) {
+ return tokens[tokenPos++];
}
+ return null;
}
/**
- * Internal method to performs the tokenization.
- * <p>
- * Most users of this class do not need to call this method. This method will be called automatically by other
- * (public) methods when required.
- * </p>
- * <p>
- * This method exists to allow subclasses to add code before or after the tokenization. For example, a subclass
- * could alter the character array, offset or count to be parsed, or call the tokenizer multiple times on multiple
- * strings. It is also be possible to filter the results.
- * </p>
- * <p>
- * {@code StrTokenizer} will always pass a zero offset and a count equal to the length of the array to this
- * method, however a subclass may pass other values, or even an entirely different array.
- * </p>
+ * Gets the token previous to the last returned token.
*
- * @param srcChars
- * the character array being tokenized, may be null
- * @param offset
- * the start position within the character array, must be valid
- * @param count
- * the number of characters to tokenize, must be valid
- * @return The modifiable list of String tokens, unmodifiable if null array or zero count
+ * @return The previous token
*/
- protected List<String> tokenize(final char[] srcChars, final int offset, final int count) {
- if (srcChars == null || count == 0) {
- return Collections.emptyList();
+ @Override
+ public String previous() {
+ if (hasPrevious()) {
+ return tokens[--tokenPos];
}
- final TextStringBuilder buf = new TextStringBuilder();
- final List<String> tokenList = new ArrayList<>();
- int pos = offset;
-
- // loop around the entire buffer
- while (pos >= 0 && pos < count) {
- // find next token
- pos = readNextToken(srcChars, pos, count, buf, tokenList);
+ throw new NoSuchElementException();
+ }
- // handle case where end of string is a delimiter
- if (pos >= count) {
- addToken(tokenList, StringUtils.EMPTY);
- }
- }
- return tokenList;
+ /**
+ * Gets the index of the previous token.
+ *
+ * @return The previous token index
+ */
+ @Override
+ public int previousIndex() {
+ return tokenPos - 1;
}
/**
- * Adds a token to a list, paying attention to the parameters we've set.
+ * Gets the previous token from the String.
*
- * @param list
- * the list to add to
- * @param tok
- * the token to add
+ * @return The previous sequential token, or null when no more tokens are found
*/
- private void addToken(final List<String> list, String tok) {
- if (tok == null || tok.isEmpty()) {
- if (isIgnoreEmptyTokens()) {
- return;
- }
- if (isEmptyTokenAsNull()) {
- tok = null;
- }
+ public String previousToken() {
+ if (hasPrevious()) {
+ return tokens[--tokenPos];
}
- list.add(tok);
+ return null;
}
/**
@@ -845,37 +861,79 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
}
/**
- * Checks if the characters at the index specified match the quote already matched in readNextToken().
+ * Unsupported ListIterator operation.
+ *
+ * @throws UnsupportedOperationException
+ * always
+ */
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException("remove() is unsupported");
+ }
+
+ /**
+ * Resets this tokenizer, forgetting all parsing and iteration already completed.
+ * <p>
+ * This method allows the same tokenizer to be reused for the same String.
+ *
+ * @return this, to enable chaining
+ */
+ public StringTokenizer reset() {
+ tokenPos = 0;
+ tokens = null;
+ return this;
+ }
+
+ /**
+ * Reset this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the
+ * same settings on multiple input lines.
+ *
+ * @param input
+ * the new character array to tokenize, not cloned, null sets no text to parse
+ * @return this, to enable chaining
+ */
+ public StringTokenizer reset(final char[] input) {
+ reset();
+ this.chars = input != null ? input.clone() : null;
+ return this;
+ }
+
+ /**
+ * Reset this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the
+ * same settings on multiple input lines.
+ *
+ * @param input
+ * the new string to tokenize, null sets no text to parse
+ * @return this, to enable chaining
+ */
+ public StringTokenizer reset(final String input) {
+ reset();
+ this.chars = input != null ? input.toCharArray() : null;
+ return this;
+ }
+
+ /**
+ * Unsupported ListIterator operation.
*
- * @param srcChars
- * the character array being tokenized
- * @param pos
- * the position to check for a quote
- * @param len
- * the length of the character array being tokenized
- * @param quoteStart
- * the start position of the matched quote, 0 if no quoting
- * @param quoteLen
- * the length of the matched quote, 0 if no quoting
- * @return true if a quote is matched
+ * @param obj
+ * this parameter ignored.
+ * @throws UnsupportedOperationException
+ * always
*/
- private boolean isQuote(final char[] srcChars, final int pos, final int len, final int quoteStart,
- final int quoteLen) {
- for (int i = 0; i < quoteLen; i++) {
- if (pos + i >= len || srcChars[pos + i] != srcChars[quoteStart + i]) {
- return false;
- }
- }
- return true;
+ @Override
+ public void set(final String obj) {
+ throw new UnsupportedOperationException("set() is unsupported");
}
/**
- * Gets the field delimiter matcher.
+ * Sets the field delimiter character.
*
- * @return The delimiter matcher in use
+ * @param delim
+ * the delimiter character to use
+ * @return this, to enable chaining
*/
- public StringMatcher getDelimiterMatcher() {
- return this.delimMatcher;
+ public StringTokenizer setDelimiterChar(final char delim) {
+ return setDelimiterMatcher(StringMatcherFactory.INSTANCE.charMatcher(delim));
}
/**
@@ -894,17 +952,6 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
}
/**
- * Sets the field delimiter character.
- *
- * @param delim
- * the delimiter character to use
- * @return this, to enable chaining
- */
- public StringTokenizer setDelimiterChar(final char delim) {
- return setDelimiterMatcher(StringMatcherFactory.INSTANCE.charMatcher(delim));
- }
-
- /**
* Sets the field delimiter string.
*
* @param delim
@@ -916,60 +963,29 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
}
/**
- * Gets the quote matcher currently in use.
- * <p>
- * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data. The
- * default value is '"' (double quote).
- * </p>
- *
- * @return The quote matcher in use
- */
- public StringMatcher getQuoteMatcher() {
- return quoteMatcher;
- }
-
- /**
- * Set the quote matcher to use.
- * <p>
- * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data.
- * </p>
+ * Sets whether the tokenizer should return empty tokens as null. The default for this property is false.
*
- * @param quote
- * the quote matcher to use, null ignored
+ * @param emptyAsNull
+ * whether empty tokens are returned as null
* @return this, to enable chaining
*/
- public StringTokenizer setQuoteMatcher(final StringMatcher quote) {
- if (quote != null) {
- this.quoteMatcher = quote;
- }
+ public StringTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) {
+ this.emptyAsNull = emptyAsNull;
return this;
}
/**
- * Sets the quote character to use.
+ * Set the character to ignore.
* <p>
- * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data.
+ * This character is ignored when parsing the String, unless it is within a quoted region.
* </p>
*
- * @param quote
- * the quote character to use
+ * @param ignored
+ * the ignored character to use
* @return this, to enable chaining
*/
- public StringTokenizer setQuoteChar(final char quote) {
- return setQuoteMatcher(StringMatcherFactory.INSTANCE.charMatcher(quote));
- }
-
- /**
- * Gets the ignored character matcher.
- * <p>
- * These characters are ignored when parsing the String, unless they are within a quoted region. The default value
- * is not to ignore anything.
- * </p>
- *
- * @return The ignored matcher in use
- */
- public StringMatcher getIgnoredMatcher() {
- return ignoredMatcher;
+ public StringTokenizer setIgnoredChar(final char ignored) {
+ return setIgnoredMatcher(StringMatcherFactory.INSTANCE.charMatcher(ignored));
}
/**
@@ -990,30 +1006,46 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
}
/**
- * Set the character to ignore.
+ * Sets whether the tokenizer should ignore and not return empty tokens. The default for this property is true.
+ *
+ * @param ignoreEmptyTokens
+ * whether empty tokens are not returned
+ * @return this, to enable chaining
+ */
+ public StringTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) {
+ this.ignoreEmptyTokens = ignoreEmptyTokens;
+ return this;
+ }
+
+ /**
+ * Sets the quote character to use.
* <p>
- * This character is ignored when parsing the String, unless it is within a quoted region.
+ * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data.
* </p>
*
- * @param ignored
- * the ignored character to use
+ * @param quote
+ * the quote character to use
* @return this, to enable chaining
*/
- public StringTokenizer setIgnoredChar(final char ignored) {
- return setIgnoredMatcher(StringMatcherFactory.INSTANCE.charMatcher(ignored));
+ public StringTokenizer setQuoteChar(final char quote) {
+ return setQuoteMatcher(StringMatcherFactory.INSTANCE.charMatcher(quote));
}
/**
- * Gets the trimmer character matcher.
+ * Set the quote matcher to use.
* <p>
- * These characters are trimmed off on each side of the delimiter until the token or quote is found. The default
- * value is not to trim anything.
+ * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data.
* </p>
*
- * @return The trimmer matcher in use
+ * @param quote
+ * the quote matcher to use, null ignored
+ * @return this, to enable chaining
*/
- public StringMatcher getTrimmerMatcher() {
- return trimmerMatcher;
+ public StringTokenizer setQuoteMatcher(final StringMatcher quote) {
+ if (quote != null) {
+ this.quoteMatcher = quote;
+ }
+ return this;
}
/**
@@ -1033,90 +1065,58 @@ public class StringTokenizer implements ListIterator<String>, Cloneable {
}
/**
- * Gets whether the tokenizer currently returns empty tokens as null. The default for this property is false.
- *
- * @return true if empty tokens are returned as null
- */
- public boolean isEmptyTokenAsNull() {
- return this.emptyAsNull;
- }
-
- /**
- * Sets whether the tokenizer should return empty tokens as null. The default for this property is false.
- *
- * @param emptyAsNull
- * whether empty tokens are returned as null
- * @return this, to enable chaining
- */
- public StringTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) {
- this.emptyAsNull = emptyAsNull;
- return this;
- }
-
- /**
- * Gets whether the tokenizer currently ignores empty tokens. The default for this property is true.
- *
- * @return true if empty tokens are not returned
- */
- public boolean isIgnoreEmptyTokens() {
- return ignoreEmptyTokens;
- }
-
- /**
- * Sets whether the tokenizer should ignore and not return empty tokens. The default for this property is true.
+ * Gets the number of tokens found in the String.
*
- * @param ignoreEmptyTokens
- * whether empty tokens are not returned
- * @return this, to enable chaining
+ * @return The number of matched tokens
*/
- public StringTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) {
- this.ignoreEmptyTokens = ignoreEmptyTokens;
- return this;
+ public int size() {
+ checkTokenized();
+ return tokens.length;
}
/**
- * Gets the String content that the tokenizer is parsing.
+ * Internal method to performs the tokenization.
+ * <p>
+ * Most users of this class do not need to call this method. This method will be called automatically by other
+ * (public) methods when required.
+ * </p>
+ * <p>
+ * This method exists to allow subclasses to add code before or after the tokenization. For example, a subclass
+ * could alter the character array, offset or count to be parsed, or call the tokenizer multiple times on multiple
+ * strings. It is also be possible to filter the results.
+ * </p>
+ * <p>
+ * {@code StrTokenizer} will always pass a zero offset and a count equal to the length of the array to this
+ * method, however a subclass may pass other values, or even an entirely different array.
+ * </p>
*
- * @return The string content being parsed
+ * @param srcChars
+ * the character array being tokenized, may be null
+ * @param offset
+ * the start position within the character array, must be valid
+ * @param count
+ * the number of characters to tokenize, must be valid
+ * @return The modifiable list of String tokens, unmodifiable if null array or zero count
*/
- public String getContent() {
- if (chars == null) {
- return null;
+ protected List<String> tokenize(final char[] srcChars, final int offset, final int count) {
+ if (srcChars == null || count == 0) {
+ return Collections.emptyList();
}
- return new String(chars);
- }
+ final TextStringBuilder buf = new TextStringBuilder();
+ final List<String> tokenList = new ArrayList<>();
+ int pos = offset;
- /**
- * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token
- * list. If a {@link CloneNotSupportedException} is caught, return {@code null}.
- *
- * @return a new instance of this Tokenizer which has been reset.
- */
- @Override
- public Object clone() {
- try {
- return cloneReset();
- } catch (final CloneNotSupportedException ex) {
- return null;
- }
- }
+ // loop around the entire buffer
+ while (pos >= 0 && pos < count) {
+ // find next token
+ pos = readNextToken(srcChars, pos, count, buf, tokenList);
- /**
- * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token
- * list.
- *
- * @return a new instance of this Tokenizer which has been reset.
- * @throws CloneNotSupportedException
- * if there is a problem cloning
- */
- Object cloneReset() throws CloneNotSupportedException {
- // this method exists to enable 100% test coverage
- final StringTokenizer cloned = (StringTokenizer) super.clone();
- if (cloned.chars != null) {
- cloned.chars = cloned.chars.clone();
+ // handle case where end of string is a delimiter
+ if (pos >= count) {
+ addToken(tokenList, StringUtils.EMPTY);
+ }
}
- cloned.reset();
- return cloned;
+ return tokenList;
}
/**