001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.text; 018 019import java.io.IOException; 020import java.io.Reader; 021import java.io.Serializable; 022import java.io.Writer; 023import java.nio.CharBuffer; 024import java.util.Iterator; 025import java.util.List; 026import java.util.Objects; 027 028/** 029 * Builds a string from constituent parts providing a more flexible and powerful API 030 * than StringBuffer. 031 * <p> 032 * The main differences from StringBuffer/StringBuilder are: 033 * </p> 034 * <ul> 035 * <li>Not synchronized</li> 036 * <li>Not final</li> 037 * <li>Subclasses have direct access to character array</li> 038 * <li>Additional methods 039 * <ul> 040 * <li>appendWithSeparators - adds an array of values, with a separator</li> 041 * <li>appendPadding - adds a length padding characters</li> 042 * <li>appendFixedLength - adds a fixed width field to the builder</li> 043 * <li>toCharArray/getChars - simpler ways to get a range of the character array</li> 044 * <li>delete - delete char or string</li> 045 * <li>replace - search and replace for a char or string</li> 046 * <li>leftString/rightString/midString - substring without exceptions</li> 047 * <li>contains - whether the builder contains a char or string</li> 048 * <li>size/clear/isEmpty - collections style API methods</li> 049 * </ul> 050 * </li> 051 * <li>Views 052 * <ul> 053 * <li>asTokenizer - uses the internal buffer as the source of a StrTokenizer</li> 054 * <li>asReader - uses the internal buffer as the source of a Reader</li> 055 * <li>asWriter - allows a Writer to write directly to the internal buffer</li> 056 * </ul> 057 * </li> 058 * </ul> 059 * <p> 060 * The aim has been to provide an API that mimics very closely what StringBuffer 061 * provides, but with additional methods. It should be noted that some edge cases, 062 * with invalid indices or null input, have been altered - see individual methods. 063 * The biggest of these changes is that by default, null will not output the text 064 * 'null'. This can be controlled by a property, {@link #setNullText(String)}. 065 * </p> 066 * 067 * @since 1.0 068 * 069 */ 070public class StrBuilder implements CharSequence, Appendable, Serializable, Builder<String> { 071 072 /** 073 * The extra capacity for new builders. 074 */ 075 static final int CAPACITY = 32; 076 077 /** 078 * Required for serialization support. 079 * 080 * @see java.io.Serializable 081 */ 082 private static final long serialVersionUID = 7628716375283629643L; 083 084 /** Internal data storage. */ 085 char[] buffer; // package-protected for test code use only 086 /** Current size of the buffer. */ 087 private int size; 088 /** The new line. */ 089 private String newLine; 090 /** The null text. */ 091 private String nullText; 092 093 //----------------------------------------------------------------------- 094 /** 095 * Constructor that creates an empty builder initial capacity 32 characters. 096 */ 097 public StrBuilder() { 098 this(CAPACITY); 099 } 100 101 /** 102 * Constructor that creates an empty builder the specified initial capacity. 103 * 104 * @param initialCapacity the initial capacity, zero or less will be converted to 32 105 */ 106 public StrBuilder(int initialCapacity) { 107 super(); 108 if (initialCapacity <= 0) { 109 initialCapacity = CAPACITY; 110 } 111 buffer = new char[initialCapacity]; 112 } 113 114 /** 115 * Constructor that creates a builder from the string, allocating 116 * 32 extra characters for growth. 117 * 118 * @param str the string to copy, null treated as blank string 119 */ 120 public StrBuilder(final String str) { 121 super(); 122 if (str == null) { 123 buffer = new char[CAPACITY]; 124 } else { 125 buffer = new char[str.length() + CAPACITY]; 126 append(str); 127 } 128 } 129 130 //----------------------------------------------------------------------- 131 /** 132 * Gets the text to be appended when a new line is added. 133 * 134 * @return the new line text, null means use system default 135 */ 136 public String getNewLineText() { 137 return newLine; 138 } 139 140 /** 141 * Sets the text to be appended when a new line is added. 142 * 143 * @param newLine the new line text, null means use system default 144 * @return this, to enable chaining 145 */ 146 public StrBuilder setNewLineText(final String newLine) { 147 this.newLine = newLine; 148 return this; 149 } 150 151 //----------------------------------------------------------------------- 152 /** 153 * Gets the text to be appended when null is added. 154 * 155 * @return the null text, null means no append 156 */ 157 public String getNullText() { 158 return nullText; 159 } 160 161 /** 162 * Sets the text to be appended when null is added. 163 * 164 * @param nullText the null text, null means no append 165 * @return this, to enable chaining 166 */ 167 public StrBuilder setNullText(String nullText) { 168 if (nullText != null && nullText.isEmpty()) { 169 nullText = null; 170 } 171 this.nullText = nullText; 172 return this; 173 } 174 175 //----------------------------------------------------------------------- 176 /** 177 * Gets the length of the string builder. 178 * 179 * @return the length 180 */ 181 @Override 182 public int length() { 183 return size; 184 } 185 186 /** 187 * Updates the length of the builder by either dropping the last characters 188 * or adding filler of Unicode zero. 189 * 190 * @param length the length to set to, must be zero or positive 191 * @return this, to enable chaining 192 * @throws IndexOutOfBoundsException if the length is negative 193 */ 194 public StrBuilder setLength(final int length) { 195 if (length < 0) { 196 throw new StringIndexOutOfBoundsException(length); 197 } 198 if (length < size) { 199 size = length; 200 } else if (length > size) { 201 ensureCapacity(length); 202 final int oldEnd = size; 203 final int newEnd = length; 204 size = length; 205 for (int i = oldEnd; i < newEnd; i++) { 206 buffer[i] = '\0'; 207 } 208 } 209 return this; 210 } 211 212 //----------------------------------------------------------------------- 213 /** 214 * Gets the current size of the internal character array buffer. 215 * 216 * @return the capacity 217 */ 218 public int capacity() { 219 return buffer.length; 220 } 221 222 /** 223 * Checks the capacity and ensures that it is at least the size specified. 224 * 225 * @param capacity the capacity to ensure 226 * @return this, to enable chaining 227 */ 228 public StrBuilder ensureCapacity(final int capacity) { 229 if (capacity > buffer.length) { 230 final char[] old = buffer; 231 buffer = new char[capacity * 2]; 232 System.arraycopy(old, 0, buffer, 0, size); 233 } 234 return this; 235 } 236 237 /** 238 * Minimizes the capacity to the actual length of the string. 239 * 240 * @return this, to enable chaining 241 */ 242 public StrBuilder minimizeCapacity() { 243 if (buffer.length > length()) { 244 final char[] old = buffer; 245 buffer = new char[length()]; 246 System.arraycopy(old, 0, buffer, 0, size); 247 } 248 return this; 249 } 250 251 //----------------------------------------------------------------------- 252 /** 253 * Gets the length of the string builder. 254 * <p> 255 * This method is the same as {@link #length()} and is provided to match the 256 * API of Collections. 257 * 258 * @return the length 259 */ 260 public int size() { 261 return size; 262 } 263 264 /** 265 * Checks is the string builder is empty (convenience Collections API style method). 266 * <p> 267 * This method is the same as checking {@link #length()} and is provided to match the 268 * API of Collections. 269 * 270 * @return <code>true</code> if the size is <code>0</code>. 271 */ 272 public boolean isEmpty() { 273 return size == 0; 274 } 275 276 /** 277 * Clears the string builder (convenience Collections API style method). 278 * <p> 279 * This method does not reduce the size of the internal character buffer. 280 * To do that, call <code>clear()</code> followed by {@link #minimizeCapacity()}. 281 * <p> 282 * This method is the same as {@link #setLength(int)} called with zero 283 * and is provided to match the API of Collections. 284 * 285 * @return this, to enable chaining 286 */ 287 public StrBuilder clear() { 288 size = 0; 289 return this; 290 } 291 292 //----------------------------------------------------------------------- 293 /** 294 * Gets the character at the specified index. 295 * 296 * @see #setCharAt(int, char) 297 * @see #deleteCharAt(int) 298 * @param index the index to retrieve, must be valid 299 * @return the character at the index 300 * @throws IndexOutOfBoundsException if the index is invalid 301 */ 302 @Override 303 public char charAt(final int index) { 304 if (index < 0 || index >= length()) { 305 throw new StringIndexOutOfBoundsException(index); 306 } 307 return buffer[index]; 308 } 309 310 /** 311 * Sets the character at the specified index. 312 * 313 * @see #charAt(int) 314 * @see #deleteCharAt(int) 315 * @param index the index to set 316 * @param ch the new character 317 * @return this, to enable chaining 318 * @throws IndexOutOfBoundsException if the index is invalid 319 */ 320 public StrBuilder setCharAt(final int index, final char ch) { 321 if (index < 0 || index >= length()) { 322 throw new StringIndexOutOfBoundsException(index); 323 } 324 buffer[index] = ch; 325 return this; 326 } 327 328 /** 329 * Deletes the character at the specified index. 330 * 331 * @see #charAt(int) 332 * @see #setCharAt(int, char) 333 * @param index the index to delete 334 * @return this, to enable chaining 335 * @throws IndexOutOfBoundsException if the index is invalid 336 */ 337 public StrBuilder deleteCharAt(final int index) { 338 if (index < 0 || index >= size) { 339 throw new StringIndexOutOfBoundsException(index); 340 } 341 deleteImpl(index, index + 1, 1); 342 return this; 343 } 344 345 //----------------------------------------------------------------------- 346 /** 347 * Copies the builder's character array into a new character array. 348 * 349 * @return a new array that represents the contents of the builder 350 */ 351 public char[] toCharArray() { 352 if (size == 0) { 353 return new char[0]; 354 } 355 final char[] chars = new char[size]; 356 System.arraycopy(buffer, 0, chars, 0, size); 357 return chars; 358 } 359 360 /** 361 * Copies part of the builder's character array into a new character array. 362 * 363 * @param startIndex the start index, inclusive, must be valid 364 * @param endIndex the end index, exclusive, must be valid except that 365 * if too large it is treated as end of string 366 * @return a new array that holds part of the contents of the builder 367 * @throws IndexOutOfBoundsException if startIndex is invalid, 368 * or if endIndex is invalid (but endIndex greater than size is valid) 369 */ 370 public char[] toCharArray(final int startIndex, int endIndex) { 371 endIndex = validateRange(startIndex, endIndex); 372 final int len = endIndex - startIndex; 373 if (len == 0) { 374 return new char[0]; 375 } 376 final char[] chars = new char[len]; 377 System.arraycopy(buffer, startIndex, chars, 0, len); 378 return chars; 379 } 380 381 /** 382 * Copies the character array into the specified array. 383 * 384 * @param destination the destination array, null will cause an array to be created 385 * @return the input array, unless that was null or too small 386 */ 387 public char[] getChars(char[] destination) { 388 final int len = length(); 389 if (destination == null || destination.length < len) { 390 destination = new char[len]; 391 } 392 System.arraycopy(buffer, 0, destination, 0, len); 393 return destination; 394 } 395 396 /** 397 * Copies the character array into the specified array. 398 * 399 * @param startIndex first index to copy, inclusive, must be valid 400 * @param endIndex last index, exclusive, must be valid 401 * @param destination the destination array, must not be null or too small 402 * @param destinationIndex the index to start copying in destination 403 * @throws NullPointerException if the array is null 404 * @throws IndexOutOfBoundsException if any index is invalid 405 */ 406 public void getChars(final int startIndex, 407 final int endIndex, 408 final char[] destination, 409 final int destinationIndex) { 410 if (startIndex < 0) { 411 throw new StringIndexOutOfBoundsException(startIndex); 412 } 413 if (endIndex < 0 || endIndex > length()) { 414 throw new StringIndexOutOfBoundsException(endIndex); 415 } 416 if (startIndex > endIndex) { 417 throw new StringIndexOutOfBoundsException("end < start"); 418 } 419 System.arraycopy(buffer, startIndex, destination, destinationIndex, endIndex - startIndex); 420 } 421 422 //----------------------------------------------------------------------- 423 /** 424 * If possible, reads chars from the provided {@link Readable} directly into underlying 425 * character buffer without making extra copies. 426 * 427 * @param readable object to read from 428 * @return the number of characters read 429 * @throws IOException if an I/O error occurs 430 * 431 * @see #appendTo(Appendable) 432 */ 433 public int readFrom(final Readable readable) throws IOException { 434 final int oldSize = size; 435 if (readable instanceof Reader) { 436 final Reader r = (Reader) readable; 437 ensureCapacity(size + 1); 438 int read; 439 while ((read = r.read(buffer, size, buffer.length - size)) != -1) { 440 size += read; 441 ensureCapacity(size + 1); 442 } 443 } else if (readable instanceof CharBuffer) { 444 final CharBuffer cb = (CharBuffer) readable; 445 final int remaining = cb.remaining(); 446 ensureCapacity(size + remaining); 447 cb.get(buffer, size, remaining); 448 size += remaining; 449 } else { 450 while (true) { 451 ensureCapacity(size + 1); 452 final CharBuffer buf = CharBuffer.wrap(buffer, size, buffer.length - size); 453 final int read = readable.read(buf); 454 if (read == -1) { 455 break; 456 } 457 size += read; 458 } 459 } 460 return size - oldSize; 461 } 462 463 //----------------------------------------------------------------------- 464 /** 465 * Appends the new line string to this string builder. 466 * <p> 467 * The new line string can be altered using {@link #setNewLineText(String)}. 468 * This might be used to force the output to always use Unix line endings 469 * even when on Windows. 470 * 471 * @return this, to enable chaining 472 */ 473 public StrBuilder appendNewLine() { 474 if (newLine == null) { 475 append(System.lineSeparator()); 476 return this; 477 } 478 return append(newLine); 479 } 480 481 /** 482 * Appends the text representing <code>null</code> to this string builder. 483 * 484 * @return this, to enable chaining 485 */ 486 public StrBuilder appendNull() { 487 if (nullText == null) { 488 return this; 489 } 490 return append(nullText); 491 } 492 493 /** 494 * Appends an object to this string builder. 495 * Appending null will call {@link #appendNull()}. 496 * 497 * @param obj the object to append 498 * @return this, to enable chaining 499 */ 500 public StrBuilder append(final Object obj) { 501 if (obj == null) { 502 return appendNull(); 503 } 504 if (obj instanceof CharSequence) { 505 return append((CharSequence) obj); 506 } 507 return append(obj.toString()); 508 } 509 510 /** 511 * Appends a CharSequence to this string builder. 512 * Appending null will call {@link #appendNull()}. 513 * 514 * @param seq the CharSequence to append 515 * @return this, to enable chaining 516 */ 517 @Override 518 public StrBuilder append(final CharSequence seq) { 519 if (seq == null) { 520 return appendNull(); 521 } 522 if (seq instanceof StrBuilder) { 523 return append((StrBuilder) seq); 524 } 525 if (seq instanceof StringBuilder) { 526 return append((StringBuilder) seq); 527 } 528 if (seq instanceof StringBuffer) { 529 return append((StringBuffer) seq); 530 } 531 if (seq instanceof CharBuffer) { 532 return append((CharBuffer) seq); 533 } 534 return append(seq.toString()); 535 } 536 537 /** 538 * Appends part of a CharSequence to this string builder. 539 * Appending null will call {@link #appendNull()}. 540 * 541 * @param seq the CharSequence to append 542 * @param startIndex the start index, inclusive, must be valid 543 * @param length the length to append, must be valid 544 * @return this, to enable chaining 545 */ 546 @Override 547 public StrBuilder append(final CharSequence seq, final int startIndex, final int length) { 548 if (seq == null) { 549 return appendNull(); 550 } 551 return append(seq.toString(), startIndex, length); 552 } 553 554 /** 555 * Appends a string to this string builder. 556 * Appending null will call {@link #appendNull()}. 557 * 558 * @param str the string to append 559 * @return this, to enable chaining 560 */ 561 public StrBuilder append(final String str) { 562 if (str == null) { 563 return appendNull(); 564 } 565 final int strLen = str.length(); 566 if (strLen > 0) { 567 final int len = length(); 568 ensureCapacity(len + strLen); 569 str.getChars(0, strLen, buffer, len); 570 size += strLen; 571 } 572 return this; 573 } 574 575 576 /** 577 * Appends part of a string to this string builder. 578 * Appending null will call {@link #appendNull()}. 579 * 580 * @param str the string to append 581 * @param startIndex the start index, inclusive, must be valid 582 * @param length the length to append, must be valid 583 * @return this, to enable chaining 584 */ 585 public StrBuilder append(final String str, final int startIndex, final int length) { 586 if (str == null) { 587 return appendNull(); 588 } 589 if (startIndex < 0 || startIndex > str.length()) { 590 throw new StringIndexOutOfBoundsException("startIndex must be valid"); 591 } 592 if (length < 0 || (startIndex + length) > str.length()) { 593 throw new StringIndexOutOfBoundsException("length must be valid"); 594 } 595 if (length > 0) { 596 final int len = length(); 597 ensureCapacity(len + length); 598 str.getChars(startIndex, startIndex + length, buffer, len); 599 size += length; 600 } 601 return this; 602 } 603 604 /** 605 * Calls {@link String#format(String, Object...)} and appends the result. 606 * 607 * @param format the format string 608 * @param objs the objects to use in the format string 609 * @return {@code this} to enable chaining 610 * @see String#format(String, Object...) 611 */ 612 public StrBuilder append(final String format, final Object... objs) { 613 return append(String.format(format, objs)); 614 } 615 616 /** 617 * Appends the contents of a char buffer to this string builder. 618 * Appending null will call {@link #appendNull()}. 619 * 620 * @param buf the char buffer to append 621 * @return this, to enable chaining 622 */ 623 public StrBuilder append(final CharBuffer buf) { 624 if (buf == null) { 625 return appendNull(); 626 } 627 if (buf.hasArray()) { 628 final int length = buf.remaining(); 629 final int len = length(); 630 ensureCapacity(len + length); 631 System.arraycopy(buf.array(), buf.arrayOffset() + buf.position(), buffer, len, length); 632 size += length; 633 } else { 634 append(buf.toString()); 635 } 636 return this; 637 } 638 639 /** 640 * Appends the contents of a char buffer to this string builder. 641 * Appending null will call {@link #appendNull()}. 642 * 643 * @param buf the char buffer to append 644 * @param startIndex the start index, inclusive, must be valid 645 * @param length the length to append, must be valid 646 * @return this, to enable chaining 647 */ 648 public StrBuilder append(final CharBuffer buf, final int startIndex, final int length) { 649 if (buf == null) { 650 return appendNull(); 651 } 652 if (buf.hasArray()) { 653 final int totalLength = buf.remaining(); 654 if (startIndex < 0 || startIndex > totalLength) { 655 throw new StringIndexOutOfBoundsException("startIndex must be valid"); 656 } 657 if (length < 0 || (startIndex + length) > totalLength) { 658 throw new StringIndexOutOfBoundsException("length must be valid"); 659 } 660 final int len = length(); 661 ensureCapacity(len + length); 662 System.arraycopy(buf.array(), buf.arrayOffset() + buf.position() + startIndex, buffer, len, length); 663 size += length; 664 } else { 665 append(buf.toString(), startIndex, length); 666 } 667 return this; 668 } 669 670 /** 671 * Appends a string buffer to this string builder. 672 * Appending null will call {@link #appendNull()}. 673 * 674 * @param str the string buffer to append 675 * @return this, to enable chaining 676 */ 677 public StrBuilder append(final StringBuffer str) { 678 if (str == null) { 679 return appendNull(); 680 } 681 final int strLen = str.length(); 682 if (strLen > 0) { 683 final int len = length(); 684 ensureCapacity(len + strLen); 685 str.getChars(0, strLen, buffer, len); 686 size += strLen; 687 } 688 return this; 689 } 690 691 /** 692 * Appends part of a string buffer to this string builder. 693 * Appending null will call {@link #appendNull()}. 694 * 695 * @param str the string to append 696 * @param startIndex the start index, inclusive, must be valid 697 * @param length the length to append, must be valid 698 * @return this, to enable chaining 699 */ 700 public StrBuilder append(final StringBuffer str, final int startIndex, final int length) { 701 if (str == null) { 702 return appendNull(); 703 } 704 if (startIndex < 0 || startIndex > str.length()) { 705 throw new StringIndexOutOfBoundsException("startIndex must be valid"); 706 } 707 if (length < 0 || (startIndex + length) > str.length()) { 708 throw new StringIndexOutOfBoundsException("length must be valid"); 709 } 710 if (length > 0) { 711 final int len = length(); 712 ensureCapacity(len + length); 713 str.getChars(startIndex, startIndex + length, buffer, len); 714 size += length; 715 } 716 return this; 717 } 718 719 /** 720 * Appends a StringBuilder to this string builder. 721 * Appending null will call {@link #appendNull()}. 722 * 723 * @param str the StringBuilder to append 724 * @return this, to enable chaining 725 */ 726 public StrBuilder append(final StringBuilder str) { 727 if (str == null) { 728 return appendNull(); 729 } 730 final int strLen = str.length(); 731 if (strLen > 0) { 732 final int len = length(); 733 ensureCapacity(len + strLen); 734 str.getChars(0, strLen, buffer, len); 735 size += strLen; 736 } 737 return this; 738 } 739 740 /** 741 * Appends part of a StringBuilder to this string builder. 742 * Appending null will call {@link #appendNull()}. 743 * 744 * @param str the StringBuilder to append 745 * @param startIndex the start index, inclusive, must be valid 746 * @param length the length to append, must be valid 747 * @return this, to enable chaining 748 */ 749 public StrBuilder append(final StringBuilder str, final int startIndex, final int length) { 750 if (str == null) { 751 return appendNull(); 752 } 753 if (startIndex < 0 || startIndex > str.length()) { 754 throw new StringIndexOutOfBoundsException("startIndex must be valid"); 755 } 756 if (length < 0 || (startIndex + length) > str.length()) { 757 throw new StringIndexOutOfBoundsException("length must be valid"); 758 } 759 if (length > 0) { 760 final int len = length(); 761 ensureCapacity(len + length); 762 str.getChars(startIndex, startIndex + length, buffer, len); 763 size += length; 764 } 765 return this; 766 } 767 768 /** 769 * Appends another string builder to this string builder. 770 * Appending null will call {@link #appendNull()}. 771 * 772 * @param str the string builder to append 773 * @return this, to enable chaining 774 */ 775 public StrBuilder append(final StrBuilder str) { 776 if (str == null) { 777 return appendNull(); 778 } 779 final int strLen = str.length(); 780 if (strLen > 0) { 781 final int len = length(); 782 ensureCapacity(len + strLen); 783 System.arraycopy(str.buffer, 0, buffer, len, strLen); 784 size += strLen; 785 } 786 return this; 787 } 788 789 /** 790 * Appends part of a string builder to this string builder. 791 * Appending null will call {@link #appendNull()}. 792 * 793 * @param str the string to append 794 * @param startIndex the start index, inclusive, must be valid 795 * @param length the length to append, must be valid 796 * @return this, to enable chaining 797 */ 798 public StrBuilder append(final StrBuilder str, final int startIndex, final int length) { 799 if (str == null) { 800 return appendNull(); 801 } 802 if (startIndex < 0 || startIndex > str.length()) { 803 throw new StringIndexOutOfBoundsException("startIndex must be valid"); 804 } 805 if (length < 0 || (startIndex + length) > str.length()) { 806 throw new StringIndexOutOfBoundsException("length must be valid"); 807 } 808 if (length > 0) { 809 final int len = length(); 810 ensureCapacity(len + length); 811 str.getChars(startIndex, startIndex + length, buffer, len); 812 size += length; 813 } 814 return this; 815 } 816 817 /** 818 * Appends a char array to the string builder. 819 * Appending null will call {@link #appendNull()}. 820 * 821 * @param chars the char array to append 822 * @return this, to enable chaining 823 */ 824 public StrBuilder append(final char[] chars) { 825 if (chars == null) { 826 return appendNull(); 827 } 828 final int strLen = chars.length; 829 if (strLen > 0) { 830 final int len = length(); 831 ensureCapacity(len + strLen); 832 System.arraycopy(chars, 0, buffer, len, strLen); 833 size += strLen; 834 } 835 return this; 836 } 837 838 /** 839 * Appends a char array to the string builder. 840 * Appending null will call {@link #appendNull()}. 841 * 842 * @param chars the char array to append 843 * @param startIndex the start index, inclusive, must be valid 844 * @param length the length to append, must be valid 845 * @return this, to enable chaining 846 */ 847 public StrBuilder append(final char[] chars, final int startIndex, final int length) { 848 if (chars == null) { 849 return appendNull(); 850 } 851 if (startIndex < 0 || startIndex > chars.length) { 852 throw new StringIndexOutOfBoundsException("Invalid startIndex: " + length); 853 } 854 if (length < 0 || (startIndex + length) > chars.length) { 855 throw new StringIndexOutOfBoundsException("Invalid length: " + length); 856 } 857 if (length > 0) { 858 final int len = length(); 859 ensureCapacity(len + length); 860 System.arraycopy(chars, startIndex, buffer, len, length); 861 size += length; 862 } 863 return this; 864 } 865 866 /** 867 * Appends a boolean value to the string builder. 868 * 869 * @param value the value to append 870 * @return this, to enable chaining 871 */ 872 public StrBuilder append(final boolean value) { 873 if (value) { 874 ensureCapacity(size + 4); 875 buffer[size++] = 't'; 876 buffer[size++] = 'r'; 877 buffer[size++] = 'u'; 878 buffer[size++] = 'e'; 879 } else { 880 ensureCapacity(size + 5); 881 buffer[size++] = 'f'; 882 buffer[size++] = 'a'; 883 buffer[size++] = 'l'; 884 buffer[size++] = 's'; 885 buffer[size++] = 'e'; 886 } 887 return this; 888 } 889 890 /** 891 * Appends a char value to the string builder. 892 * 893 * @param ch the value to append 894 * @return this, to enable chaining 895 */ 896 @Override 897 public StrBuilder append(final char ch) { 898 final int len = length(); 899 ensureCapacity(len + 1); 900 buffer[size++] = ch; 901 return this; 902 } 903 904 /** 905 * Appends an int value to the string builder using <code>String.valueOf</code>. 906 * 907 * @param value the value to append 908 * @return this, to enable chaining 909 */ 910 public StrBuilder append(final int value) { 911 return append(String.valueOf(value)); 912 } 913 914 /** 915 * Appends a long value to the string builder using <code>String.valueOf</code>. 916 * 917 * @param value the value to append 918 * @return this, to enable chaining 919 */ 920 public StrBuilder append(final long value) { 921 return append(String.valueOf(value)); 922 } 923 924 /** 925 * Appends a float value to the string builder using <code>String.valueOf</code>. 926 * 927 * @param value the value to append 928 * @return this, to enable chaining 929 */ 930 public StrBuilder append(final float value) { 931 return append(String.valueOf(value)); 932 } 933 934 /** 935 * Appends a double value to the string builder using <code>String.valueOf</code>. 936 * 937 * @param value the value to append 938 * @return this, to enable chaining 939 */ 940 public StrBuilder append(final double value) { 941 return append(String.valueOf(value)); 942 } 943 944 //----------------------------------------------------------------------- 945 /** 946 * Appends an object followed by a new line to this string builder. 947 * Appending null will call {@link #appendNull()}. 948 * 949 * @param obj the object to append 950 * @return this, to enable chaining 951 */ 952 public StrBuilder appendln(final Object obj) { 953 return append(obj).appendNewLine(); 954 } 955 956 /** 957 * Appends a string followed by a new line to this string builder. 958 * Appending null will call {@link #appendNull()}. 959 * 960 * @param str the string to append 961 * @return this, to enable chaining 962 */ 963 public StrBuilder appendln(final String str) { 964 return append(str).appendNewLine(); 965 } 966 967 /** 968 * Appends part of a string followed by a new line to this string builder. 969 * Appending null will call {@link #appendNull()}. 970 * 971 * @param str the string to append 972 * @param startIndex the start index, inclusive, must be valid 973 * @param length the length to append, must be valid 974 * @return this, to enable chaining 975 */ 976 public StrBuilder appendln(final String str, final int startIndex, final int length) { 977 return append(str, startIndex, length).appendNewLine(); 978 } 979 980 /** 981 * Calls {@link String#format(String, Object...)} and appends the result. 982 * 983 * @param format the format string 984 * @param objs the objects to use in the format string 985 * @return {@code this} to enable chaining 986 * @see String#format(String, Object...) 987 */ 988 public StrBuilder appendln(final String format, final Object... objs) { 989 return append(format, objs).appendNewLine(); 990 } 991 992 /** 993 * Appends a string buffer followed by a new line to this string builder. 994 * Appending null will call {@link #appendNull()}. 995 * 996 * @param str the string buffer to append 997 * @return this, to enable chaining 998 */ 999 public StrBuilder appendln(final StringBuffer str) { 1000 return append(str).appendNewLine(); 1001 } 1002 1003 /** 1004 * Appends a string builder followed by a new line to this string builder. 1005 * Appending null will call {@link #appendNull()}. 1006 * 1007 * @param str the string builder to append 1008 * @return this, to enable chaining 1009 */ 1010 public StrBuilder appendln(final StringBuilder str) { 1011 return append(str).appendNewLine(); 1012 } 1013 1014 /** 1015 * Appends part of a string builder followed by a new line to this string builder. 1016 * Appending null will call {@link #appendNull()}. 1017 * 1018 * @param str the string builder to append 1019 * @param startIndex the start index, inclusive, must be valid 1020 * @param length the length to append, must be valid 1021 * @return this, to enable chaining 1022 */ 1023 public StrBuilder appendln(final StringBuilder str, final int startIndex, final int length) { 1024 return append(str, startIndex, length).appendNewLine(); 1025 } 1026 1027 /** 1028 * Appends part of a string buffer followed by a new line to this string builder. 1029 * Appending null will call {@link #appendNull()}. 1030 * 1031 * @param str the string to append 1032 * @param startIndex the start index, inclusive, must be valid 1033 * @param length the length to append, must be valid 1034 * @return this, to enable chaining 1035 */ 1036 public StrBuilder appendln(final StringBuffer str, final int startIndex, final int length) { 1037 return append(str, startIndex, length).appendNewLine(); 1038 } 1039 1040 /** 1041 * Appends another string builder followed by a new line to this string builder. 1042 * Appending null will call {@link #appendNull()}. 1043 * 1044 * @param str the string builder to append 1045 * @return this, to enable chaining 1046 */ 1047 public StrBuilder appendln(final StrBuilder str) { 1048 return append(str).appendNewLine(); 1049 } 1050 1051 /** 1052 * Appends part of a string builder followed by a new line to this string builder. 1053 * Appending null will call {@link #appendNull()}. 1054 * 1055 * @param str the string to append 1056 * @param startIndex the start index, inclusive, must be valid 1057 * @param length the length to append, must be valid 1058 * @return this, to enable chaining 1059 */ 1060 public StrBuilder appendln(final StrBuilder str, final int startIndex, final int length) { 1061 return append(str, startIndex, length).appendNewLine(); 1062 } 1063 1064 /** 1065 * Appends a char array followed by a new line to the string builder. 1066 * Appending null will call {@link #appendNull()}. 1067 * 1068 * @param chars the char array to append 1069 * @return this, to enable chaining 1070 */ 1071 public StrBuilder appendln(final char[] chars) { 1072 return append(chars).appendNewLine(); 1073 } 1074 1075 /** 1076 * Appends a char array followed by a new line to the string builder. 1077 * Appending null will call {@link #appendNull()}. 1078 * 1079 * @param chars the char array to append 1080 * @param startIndex the start index, inclusive, must be valid 1081 * @param length the length to append, must be valid 1082 * @return this, to enable chaining 1083 */ 1084 public StrBuilder appendln(final char[] chars, final int startIndex, final int length) { 1085 return append(chars, startIndex, length).appendNewLine(); 1086 } 1087 1088 /** 1089 * Appends a boolean value followed by a new line to the string builder. 1090 * 1091 * @param value the value to append 1092 * @return this, to enable chaining 1093 */ 1094 public StrBuilder appendln(final boolean value) { 1095 return append(value).appendNewLine(); 1096 } 1097 1098 /** 1099 * Appends a char value followed by a new line to the string builder. 1100 * 1101 * @param ch the value to append 1102 * @return this, to enable chaining 1103 */ 1104 public StrBuilder appendln(final char ch) { 1105 return append(ch).appendNewLine(); 1106 } 1107 1108 /** 1109 * Appends an int value followed by a new line to the string builder using <code>String.valueOf</code>. 1110 * 1111 * @param value the value to append 1112 * @return this, to enable chaining 1113 */ 1114 public StrBuilder appendln(final int value) { 1115 return append(value).appendNewLine(); 1116 } 1117 1118 /** 1119 * Appends a long value followed by a new line to the string builder using <code>String.valueOf</code>. 1120 * 1121 * @param value the value to append 1122 * @return this, to enable chaining 1123 */ 1124 public StrBuilder appendln(final long value) { 1125 return append(value).appendNewLine(); 1126 } 1127 1128 /** 1129 * Appends a float value followed by a new line to the string builder using <code>String.valueOf</code>. 1130 * 1131 * @param value the value to append 1132 * @return this, to enable chaining 1133 */ 1134 public StrBuilder appendln(final float value) { 1135 return append(value).appendNewLine(); 1136 } 1137 1138 /** 1139 * Appends a double value followed by a new line to the string builder using <code>String.valueOf</code>. 1140 * 1141 * @param value the value to append 1142 * @return this, to enable chaining 1143 */ 1144 public StrBuilder appendln(final double value) { 1145 return append(value).appendNewLine(); 1146 } 1147 1148 //----------------------------------------------------------------------- 1149 /** 1150 * Appends each item in an array to the builder without any separators. 1151 * Appending a null array will have no effect. 1152 * Each object is appended using {@link #append(Object)}. 1153 * 1154 * @param <T> the element type 1155 * @param array the array to append 1156 * @return this, to enable chaining 1157 */ 1158 public <T> StrBuilder appendAll(@SuppressWarnings("unchecked") final T... array) { 1159 /* 1160 * @SuppressWarnings used to hide warning about vararg usage. We cannot 1161 * use @SafeVarargs, since this method is not final. Using @SupressWarnings 1162 * is fine, because it isn't inherited by subclasses, so each subclass must 1163 * vouch for itself whether its use of 'array' is safe. 1164 */ 1165 if (array != null && array.length > 0) { 1166 for (final Object element : array) { 1167 append(element); 1168 } 1169 } 1170 return this; 1171 } 1172 1173 /** 1174 * Appends each item in an iterable to the builder without any separators. 1175 * Appending a null iterable will have no effect. 1176 * Each object is appended using {@link #append(Object)}. 1177 * 1178 * @param iterable the iterable to append 1179 * @return this, to enable chaining 1180 */ 1181 public StrBuilder appendAll(final Iterable<?> iterable) { 1182 if (iterable != null) { 1183 for (final Object o : iterable) { 1184 append(o); 1185 } 1186 } 1187 return this; 1188 } 1189 1190 /** 1191 * Appends each item in an iterator to the builder without any separators. 1192 * Appending a null iterator will have no effect. 1193 * Each object is appended using {@link #append(Object)}. 1194 * 1195 * @param it the iterator to append 1196 * @return this, to enable chaining 1197 */ 1198 public StrBuilder appendAll(final Iterator<?> it) { 1199 if (it != null) { 1200 while (it.hasNext()) { 1201 append(it.next()); 1202 } 1203 } 1204 return this; 1205 } 1206 1207 //----------------------------------------------------------------------- 1208 /** 1209 * Appends an array placing separators between each value, but 1210 * not before the first or after the last. 1211 * Appending a null array will have no effect. 1212 * Each object is appended using {@link #append(Object)}. 1213 * 1214 * @param array the array to append 1215 * @param separator the separator to use, null means no separator 1216 * @return this, to enable chaining 1217 */ 1218 public StrBuilder appendWithSeparators(final Object[] array, final String separator) { 1219 if (array != null && array.length > 0) { 1220 final String sep = Objects.toString(separator, ""); 1221 append(array[0]); 1222 for (int i = 1; i < array.length; i++) { 1223 append(sep); 1224 append(array[i]); 1225 } 1226 } 1227 return this; 1228 } 1229 1230 /** 1231 * Appends an iterable placing separators between each value, but 1232 * not before the first or after the last. 1233 * Appending a null iterable will have no effect. 1234 * Each object is appended using {@link #append(Object)}. 1235 * 1236 * @param iterable the iterable to append 1237 * @param separator the separator to use, null means no separator 1238 * @return this, to enable chaining 1239 */ 1240 public StrBuilder appendWithSeparators(final Iterable<?> iterable, final String separator) { 1241 if (iterable != null) { 1242 final String sep = Objects.toString(separator, ""); 1243 final Iterator<?> it = iterable.iterator(); 1244 while (it.hasNext()) { 1245 append(it.next()); 1246 if (it.hasNext()) { 1247 append(sep); 1248 } 1249 } 1250 } 1251 return this; 1252 } 1253 1254 /** 1255 * Appends an iterator placing separators between each value, but 1256 * not before the first or after the last. 1257 * Appending a null iterator will have no effect. 1258 * Each object is appended using {@link #append(Object)}. 1259 * 1260 * @param it the iterator to append 1261 * @param separator the separator to use, null means no separator 1262 * @return this, to enable chaining 1263 */ 1264 public StrBuilder appendWithSeparators(final Iterator<?> it, final String separator) { 1265 if (it != null) { 1266 final String sep = Objects.toString(separator, ""); 1267 while (it.hasNext()) { 1268 append(it.next()); 1269 if (it.hasNext()) { 1270 append(sep); 1271 } 1272 } 1273 } 1274 return this; 1275 } 1276 1277 //----------------------------------------------------------------------- 1278 /** 1279 * Appends a separator if the builder is currently non-empty. 1280 * Appending a null separator will have no effect. 1281 * The separator is appended using {@link #append(String)}. 1282 * <p> 1283 * This method is useful for adding a separator each time around the 1284 * loop except the first. 1285 * <pre> 1286 * for (Iterator it = list.iterator(); it.hasNext(); ) { 1287 * appendSeparator(","); 1288 * append(it.next()); 1289 * } 1290 * </pre> 1291 * Note that for this simple example, you should use 1292 * {@link #appendWithSeparators(Iterable, String)}. 1293 * 1294 * @param separator the separator to use, null means no separator 1295 * @return this, to enable chaining 1296 */ 1297 public StrBuilder appendSeparator(final String separator) { 1298 return appendSeparator(separator, null); 1299 } 1300 1301 /** 1302 * Appends one of both separators to the StrBuilder. 1303 * If the builder is currently empty it will append the defaultIfEmpty-separator 1304 * Otherwise it will append the standard-separator 1305 * 1306 * Appending a null separator will have no effect. 1307 * The separator is appended using {@link #append(String)}. 1308 * <p> 1309 * This method is for example useful for constructing queries 1310 * <pre> 1311 * StrBuilder whereClause = new StrBuilder(); 1312 * if(searchCommand.getPriority() != null) { 1313 * whereClause.appendSeparator(" and", " where"); 1314 * whereClause.append(" priority = ?") 1315 * } 1316 * if(searchCommand.getComponent() != null) { 1317 * whereClause.appendSeparator(" and", " where"); 1318 * whereClause.append(" component = ?") 1319 * } 1320 * selectClause.append(whereClause) 1321 * </pre> 1322 * 1323 * @param standard the separator if builder is not empty, null means no separator 1324 * @param defaultIfEmpty the separator if builder is empty, null means no separator 1325 * @return this, to enable chaining 1326 */ 1327 public StrBuilder appendSeparator(final String standard, final String defaultIfEmpty) { 1328 final String str = isEmpty() ? defaultIfEmpty : standard; 1329 if (str != null) { 1330 append(str); 1331 } 1332 return this; 1333 } 1334 1335 /** 1336 * Appends a separator if the builder is currently non-empty. 1337 * The separator is appended using {@link #append(char)}. 1338 * <p> 1339 * This method is useful for adding a separator each time around the 1340 * loop except the first. 1341 * <pre> 1342 * for (Iterator it = list.iterator(); it.hasNext(); ) { 1343 * appendSeparator(','); 1344 * append(it.next()); 1345 * } 1346 * </pre> 1347 * Note that for this simple example, you should use 1348 * {@link #appendWithSeparators(Iterable, String)}. 1349 * 1350 * @param separator the separator to use 1351 * @return this, to enable chaining 1352 */ 1353 public StrBuilder appendSeparator(final char separator) { 1354 if (size() > 0) { 1355 append(separator); 1356 } 1357 return this; 1358 } 1359 1360 /** 1361 * Append one of both separators to the builder 1362 * If the builder is currently empty it will append the defaultIfEmpty-separator 1363 * Otherwise it will append the standard-separator 1364 * 1365 * The separator is appended using {@link #append(char)}. 1366 * @param standard the separator if builder is not empty 1367 * @param defaultIfEmpty the separator if builder is empty 1368 * @return this, to enable chaining 1369 */ 1370 public StrBuilder appendSeparator(final char standard, final char defaultIfEmpty) { 1371 if (size() > 0) { 1372 append(standard); 1373 } else { 1374 append(defaultIfEmpty); 1375 } 1376 return this; 1377 } 1378 /** 1379 * Appends a separator to the builder if the loop index is greater than zero. 1380 * Appending a null separator will have no effect. 1381 * The separator is appended using {@link #append(String)}. 1382 * <p> 1383 * This method is useful for adding a separator each time around the 1384 * loop except the first. 1385 * </p> 1386 * <pre> 1387 * for (int i = 0; i < list.size(); i++) { 1388 * appendSeparator(",", i); 1389 * append(list.get(i)); 1390 * } 1391 * </pre> 1392 * Note that for this simple example, you should use 1393 * {@link #appendWithSeparators(Iterable, String)}. 1394 * 1395 * @param separator the separator to use, null means no separator 1396 * @param loopIndex the loop index 1397 * @return this, to enable chaining 1398 */ 1399 public StrBuilder appendSeparator(final String separator, final int loopIndex) { 1400 if (separator != null && loopIndex > 0) { 1401 append(separator); 1402 } 1403 return this; 1404 } 1405 1406 /** 1407 * Appends a separator to the builder if the loop index is greater than zero. 1408 * The separator is appended using {@link #append(char)}. 1409 * <p> 1410 * This method is useful for adding a separator each time around the 1411 * loop except the first. 1412 * </p> 1413 * <pre> 1414 * for (int i = 0; i < list.size(); i++) { 1415 * appendSeparator(",", i); 1416 * append(list.get(i)); 1417 * } 1418 * </pre> 1419 * Note that for this simple example, you should use 1420 * {@link #appendWithSeparators(Iterable, String)}. 1421 * 1422 * @param separator the separator to use 1423 * @param loopIndex the loop index 1424 * @return this, to enable chaining 1425 */ 1426 public StrBuilder appendSeparator(final char separator, final int loopIndex) { 1427 if (loopIndex > 0) { 1428 append(separator); 1429 } 1430 return this; 1431 } 1432 1433 //----------------------------------------------------------------------- 1434 /** 1435 * Appends the pad character to the builder the specified number of times. 1436 * 1437 * @param length the length to append, negative means no append 1438 * @param padChar the character to append 1439 * @return this, to enable chaining 1440 */ 1441 public StrBuilder appendPadding(final int length, final char padChar) { 1442 if (length >= 0) { 1443 ensureCapacity(size + length); 1444 for (int i = 0; i < length; i++) { 1445 buffer[size++] = padChar; 1446 } 1447 } 1448 return this; 1449 } 1450 1451 //----------------------------------------------------------------------- 1452 /** 1453 * Appends an object to the builder padding on the left to a fixed width. 1454 * The <code>toString</code> of the object is used. 1455 * If the object is larger than the length, the left hand side is lost. 1456 * If the object is null, the null text value is used. 1457 * 1458 * @param obj the object to append, null uses null text 1459 * @param width the fixed field width, zero or negative has no effect 1460 * @param padChar the pad character to use 1461 * @return this, to enable chaining 1462 */ 1463 public StrBuilder appendFixedWidthPadLeft(final Object obj, final int width, final char padChar) { 1464 if (width > 0) { 1465 ensureCapacity(size + width); 1466 String str = (obj == null ? getNullText() : obj.toString()); 1467 if (str == null) { 1468 str = ""; 1469 } 1470 final int strLen = str.length(); 1471 if (strLen >= width) { 1472 str.getChars(strLen - width, strLen, buffer, size); 1473 } else { 1474 final int padLen = width - strLen; 1475 for (int i = 0; i < padLen; i++) { 1476 buffer[size + i] = padChar; 1477 } 1478 str.getChars(0, strLen, buffer, size + padLen); 1479 } 1480 size += width; 1481 } 1482 return this; 1483 } 1484 1485 /** 1486 * Appends an object to the builder padding on the left to a fixed width. 1487 * The <code>String.valueOf</code> of the <code>int</code> value is used. 1488 * If the formatted value is larger than the length, the left hand side is lost. 1489 * 1490 * @param value the value to append 1491 * @param width the fixed field width, zero or negative has no effect 1492 * @param padChar the pad character to use 1493 * @return this, to enable chaining 1494 */ 1495 public StrBuilder appendFixedWidthPadLeft(final int value, final int width, final char padChar) { 1496 return appendFixedWidthPadLeft(String.valueOf(value), width, padChar); 1497 } 1498 1499 /** 1500 * Appends an object to the builder padding on the right to a fixed length. 1501 * The <code>toString</code> of the object is used. 1502 * If the object is larger than the length, the right hand side is lost. 1503 * If the object is null, null text value is used. 1504 * 1505 * @param obj the object to append, null uses null text 1506 * @param width the fixed field width, zero or negative has no effect 1507 * @param padChar the pad character to use 1508 * @return this, to enable chaining 1509 */ 1510 public StrBuilder appendFixedWidthPadRight(final Object obj, final int width, final char padChar) { 1511 if (width > 0) { 1512 ensureCapacity(size + width); 1513 String str = (obj == null ? getNullText() : obj.toString()); 1514 if (str == null) { 1515 str = ""; 1516 } 1517 final int strLen = str.length(); 1518 if (strLen >= width) { 1519 str.getChars(0, width, buffer, size); 1520 } else { 1521 final int padLen = width - strLen; 1522 str.getChars(0, strLen, buffer, size); 1523 for (int i = 0; i < padLen; i++) { 1524 buffer[size + strLen + i] = padChar; 1525 } 1526 } 1527 size += width; 1528 } 1529 return this; 1530 } 1531 1532 /** 1533 * Appends an object to the builder padding on the right to a fixed length. 1534 * The <code>String.valueOf</code> of the <code>int</code> value is used. 1535 * If the object is larger than the length, the right hand side is lost. 1536 * 1537 * @param value the value to append 1538 * @param width the fixed field width, zero or negative has no effect 1539 * @param padChar the pad character to use 1540 * @return this, to enable chaining 1541 */ 1542 public StrBuilder appendFixedWidthPadRight(final int value, final int width, final char padChar) { 1543 return appendFixedWidthPadRight(String.valueOf(value), width, padChar); 1544 } 1545 1546 //----------------------------------------------------------------------- 1547 /** 1548 * Inserts the string representation of an object into this builder. 1549 * Inserting null will use the stored null text value. 1550 * 1551 * @param index the index to add at, must be valid 1552 * @param obj the object to insert 1553 * @return this, to enable chaining 1554 * @throws IndexOutOfBoundsException if the index is invalid 1555 */ 1556 public StrBuilder insert(final int index, final Object obj) { 1557 if (obj == null) { 1558 return insert(index, nullText); 1559 } 1560 return insert(index, obj.toString()); 1561 } 1562 1563 /** 1564 * Inserts the string into this builder. 1565 * Inserting null will use the stored null text value. 1566 * 1567 * @param index the index to add at, must be valid 1568 * @param str the string to insert 1569 * @return this, to enable chaining 1570 * @throws IndexOutOfBoundsException if the index is invalid 1571 */ 1572 public StrBuilder insert(final int index, String str) { 1573 validateIndex(index); 1574 if (str == null) { 1575 str = nullText; 1576 } 1577 if (str != null) { 1578 final int strLen = str.length(); 1579 if (strLen > 0) { 1580 final int newSize = size + strLen; 1581 ensureCapacity(newSize); 1582 System.arraycopy(buffer, index, buffer, index + strLen, size - index); 1583 size = newSize; 1584 str.getChars(0, strLen, buffer, index); 1585 } 1586 } 1587 return this; 1588 } 1589 1590 /** 1591 * Inserts the character array into this builder. 1592 * Inserting null will use the stored null text value. 1593 * 1594 * @param index the index to add at, must be valid 1595 * @param chars the char array to insert 1596 * @return this, to enable chaining 1597 * @throws IndexOutOfBoundsException if the index is invalid 1598 */ 1599 public StrBuilder insert(final int index, final char[] chars) { 1600 validateIndex(index); 1601 if (chars == null) { 1602 return insert(index, nullText); 1603 } 1604 final int len = chars.length; 1605 if (len > 0) { 1606 ensureCapacity(size + len); 1607 System.arraycopy(buffer, index, buffer, index + len, size - index); 1608 System.arraycopy(chars, 0, buffer, index, len); 1609 size += len; 1610 } 1611 return this; 1612 } 1613 1614 /** 1615 * Inserts part of the character array into this builder. 1616 * Inserting null will use the stored null text value. 1617 * 1618 * @param index the index to add at, must be valid 1619 * @param chars the char array to insert 1620 * @param offset the offset into the character array to start at, must be valid 1621 * @param length the length of the character array part to copy, must be positive 1622 * @return this, to enable chaining 1623 * @throws IndexOutOfBoundsException if any index is invalid 1624 */ 1625 public StrBuilder insert(final int index, final char[] chars, final int offset, final int length) { 1626 validateIndex(index); 1627 if (chars == null) { 1628 return insert(index, nullText); 1629 } 1630 if (offset < 0 || offset > chars.length) { 1631 throw new StringIndexOutOfBoundsException("Invalid offset: " + offset); 1632 } 1633 if (length < 0 || offset + length > chars.length) { 1634 throw new StringIndexOutOfBoundsException("Invalid length: " + length); 1635 } 1636 if (length > 0) { 1637 ensureCapacity(size + length); 1638 System.arraycopy(buffer, index, buffer, index + length, size - index); 1639 System.arraycopy(chars, offset, buffer, index, length); 1640 size += length; 1641 } 1642 return this; 1643 } 1644 1645 /** 1646 * Inserts the value into this builder. 1647 * 1648 * @param index the index to add at, must be valid 1649 * @param value the value to insert 1650 * @return this, to enable chaining 1651 * @throws IndexOutOfBoundsException if the index is invalid 1652 */ 1653 public StrBuilder insert(int index, final boolean value) { 1654 validateIndex(index); 1655 if (value) { 1656 ensureCapacity(size + 4); 1657 System.arraycopy(buffer, index, buffer, index + 4, size - index); 1658 buffer[index++] = 't'; 1659 buffer[index++] = 'r'; 1660 buffer[index++] = 'u'; 1661 buffer[index] = 'e'; 1662 size += 4; 1663 } else { 1664 ensureCapacity(size + 5); 1665 System.arraycopy(buffer, index, buffer, index + 5, size - index); 1666 buffer[index++] = 'f'; 1667 buffer[index++] = 'a'; 1668 buffer[index++] = 'l'; 1669 buffer[index++] = 's'; 1670 buffer[index] = 'e'; 1671 size += 5; 1672 } 1673 return this; 1674 } 1675 1676 /** 1677 * Inserts the value into this builder. 1678 * 1679 * @param index the index to add at, must be valid 1680 * @param value the value to insert 1681 * @return this, to enable chaining 1682 * @throws IndexOutOfBoundsException if the index is invalid 1683 */ 1684 public StrBuilder insert(final int index, final char value) { 1685 validateIndex(index); 1686 ensureCapacity(size + 1); 1687 System.arraycopy(buffer, index, buffer, index + 1, size - index); 1688 buffer[index] = value; 1689 size++; 1690 return this; 1691 } 1692 1693 /** 1694 * Inserts the value into this builder. 1695 * 1696 * @param index the index to add at, must be valid 1697 * @param value the value to insert 1698 * @return this, to enable chaining 1699 * @throws IndexOutOfBoundsException if the index is invalid 1700 */ 1701 public StrBuilder insert(final int index, final int value) { 1702 return insert(index, String.valueOf(value)); 1703 } 1704 1705 /** 1706 * Inserts the value into this builder. 1707 * 1708 * @param index the index to add at, must be valid 1709 * @param value the value to insert 1710 * @return this, to enable chaining 1711 * @throws IndexOutOfBoundsException if the index is invalid 1712 */ 1713 public StrBuilder insert(final int index, final long value) { 1714 return insert(index, String.valueOf(value)); 1715 } 1716 1717 /** 1718 * Inserts the value into this builder. 1719 * 1720 * @param index the index to add at, must be valid 1721 * @param value the value to insert 1722 * @return this, to enable chaining 1723 * @throws IndexOutOfBoundsException if the index is invalid 1724 */ 1725 public StrBuilder insert(final int index, final float value) { 1726 return insert(index, String.valueOf(value)); 1727 } 1728 1729 /** 1730 * Inserts the value into this builder. 1731 * 1732 * @param index the index to add at, must be valid 1733 * @param value the value to insert 1734 * @return this, to enable chaining 1735 * @throws IndexOutOfBoundsException if the index is invalid 1736 */ 1737 public StrBuilder insert(final int index, final double value) { 1738 return insert(index, String.valueOf(value)); 1739 } 1740 1741 //----------------------------------------------------------------------- 1742 /** 1743 * Internal method to delete a range without validation. 1744 * 1745 * @param startIndex the start index, must be valid 1746 * @param endIndex the end index (exclusive), must be valid 1747 * @param len the length, must be valid 1748 * @throws IndexOutOfBoundsException if any index is invalid 1749 */ 1750 private void deleteImpl(final int startIndex, final int endIndex, final int len) { 1751 System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex); 1752 size -= len; 1753 } 1754 1755 /** 1756 * Deletes the characters between the two specified indices. 1757 * 1758 * @param startIndex the start index, inclusive, must be valid 1759 * @param endIndex the end index, exclusive, must be valid except 1760 * that if too large it is treated as end of string 1761 * @return this, to enable chaining 1762 * @throws IndexOutOfBoundsException if the index is invalid 1763 */ 1764 public StrBuilder delete(final int startIndex, int endIndex) { 1765 endIndex = validateRange(startIndex, endIndex); 1766 final int len = endIndex - startIndex; 1767 if (len > 0) { 1768 deleteImpl(startIndex, endIndex, len); 1769 } 1770 return this; 1771 } 1772 1773 //----------------------------------------------------------------------- 1774 /** 1775 * Deletes the character wherever it occurs in the builder. 1776 * 1777 * @param ch the character to delete 1778 * @return this, to enable chaining 1779 */ 1780 public StrBuilder deleteAll(final char ch) { 1781 for (int i = 0; i < size; i++) { 1782 if (buffer[i] == ch) { 1783 final int start = i; 1784 while (++i < size) { 1785 if (buffer[i] != ch) { 1786 break; 1787 } 1788 } 1789 final int len = i - start; 1790 deleteImpl(start, i, len); 1791 i -= len; 1792 } 1793 } 1794 return this; 1795 } 1796 1797 /** 1798 * Deletes the character wherever it occurs in the builder. 1799 * 1800 * @param ch the character to delete 1801 * @return this, to enable chaining 1802 */ 1803 public StrBuilder deleteFirst(final char ch) { 1804 for (int i = 0; i < size; i++) { 1805 if (buffer[i] == ch) { 1806 deleteImpl(i, i + 1, 1); 1807 break; 1808 } 1809 } 1810 return this; 1811 } 1812 1813 //----------------------------------------------------------------------- 1814 /** 1815 * Deletes the string wherever it occurs in the builder. 1816 * 1817 * @param str the string to delete, null causes no action 1818 * @return this, to enable chaining 1819 */ 1820 public StrBuilder deleteAll(final String str) { 1821 final int len = (str == null ? 0 : str.length()); 1822 if (len > 0) { 1823 int index = indexOf(str, 0); 1824 while (index >= 0) { 1825 deleteImpl(index, index + len, len); 1826 index = indexOf(str, index); 1827 } 1828 } 1829 return this; 1830 } 1831 1832 /** 1833 * Deletes the string wherever it occurs in the builder. 1834 * 1835 * @param str the string to delete, null causes no action 1836 * @return this, to enable chaining 1837 */ 1838 public StrBuilder deleteFirst(final String str) { 1839 final int len = (str == null ? 0 : str.length()); 1840 if (len > 0) { 1841 final int index = indexOf(str, 0); 1842 if (index >= 0) { 1843 deleteImpl(index, index + len, len); 1844 } 1845 } 1846 return this; 1847 } 1848 1849 //----------------------------------------------------------------------- 1850 /** 1851 * Deletes all parts of the builder that the matcher matches. 1852 * <p> 1853 * Matchers can be used to perform advanced deletion behaviour. 1854 * For example you could write a matcher to delete all occurrences 1855 * where the character 'a' is followed by a number. 1856 * 1857 * @param matcher the matcher to use to find the deletion, null causes no action 1858 * @return this, to enable chaining 1859 */ 1860 public StrBuilder deleteAll(final StrMatcher matcher) { 1861 return replace(matcher, null, 0, size, -1); 1862 } 1863 1864 /** 1865 * Deletes the first match within the builder using the specified matcher. 1866 * <p> 1867 * Matchers can be used to perform advanced deletion behaviour. 1868 * For example you could write a matcher to delete 1869 * where the character 'a' is followed by a number. 1870 * 1871 * @param matcher the matcher to use to find the deletion, null causes no action 1872 * @return this, to enable chaining 1873 */ 1874 public StrBuilder deleteFirst(final StrMatcher matcher) { 1875 return replace(matcher, null, 0, size, 1); 1876 } 1877 1878 //----------------------------------------------------------------------- 1879 /** 1880 * Internal method to delete a range without validation. 1881 * 1882 * @param startIndex the start index, must be valid 1883 * @param endIndex the end index (exclusive), must be valid 1884 * @param removeLen the length to remove (endIndex - startIndex), must be valid 1885 * @param insertStr the string to replace with, null means delete range 1886 * @param insertLen the length of the insert string, must be valid 1887 * @throws IndexOutOfBoundsException if any index is invalid 1888 */ 1889 private void replaceImpl(final int startIndex, 1890 final int endIndex, 1891 final int removeLen, 1892 final String insertStr, 1893 final int insertLen) { 1894 final int newSize = size - removeLen + insertLen; 1895 if (insertLen != removeLen) { 1896 ensureCapacity(newSize); 1897 System.arraycopy(buffer, endIndex, buffer, startIndex + insertLen, size - endIndex); 1898 size = newSize; 1899 } 1900 if (insertLen > 0) { 1901 insertStr.getChars(0, insertLen, buffer, startIndex); 1902 } 1903 } 1904 1905 /** 1906 * Replaces a portion of the string builder with another string. 1907 * The length of the inserted string does not have to match the removed length. 1908 * 1909 * @param startIndex the start index, inclusive, must be valid 1910 * @param endIndex the end index, exclusive, must be valid except 1911 * that if too large it is treated as end of string 1912 * @param replaceStr the string to replace with, null means delete range 1913 * @return this, to enable chaining 1914 * @throws IndexOutOfBoundsException if the index is invalid 1915 */ 1916 public StrBuilder replace(final int startIndex, int endIndex, final String replaceStr) { 1917 endIndex = validateRange(startIndex, endIndex); 1918 final int insertLen = (replaceStr == null ? 0 : replaceStr.length()); 1919 replaceImpl(startIndex, endIndex, endIndex - startIndex, replaceStr, insertLen); 1920 return this; 1921 } 1922 1923 //----------------------------------------------------------------------- 1924 /** 1925 * Replaces the search character with the replace character 1926 * throughout the builder. 1927 * 1928 * @param search the search character 1929 * @param replace the replace character 1930 * @return this, to enable chaining 1931 */ 1932 public StrBuilder replaceAll(final char search, final char replace) { 1933 if (search != replace) { 1934 for (int i = 0; i < size; i++) { 1935 if (buffer[i] == search) { 1936 buffer[i] = replace; 1937 } 1938 } 1939 } 1940 return this; 1941 } 1942 1943 /** 1944 * Replaces the first instance of the search character with the 1945 * replace character in the builder. 1946 * 1947 * @param search the search character 1948 * @param replace the replace character 1949 * @return this, to enable chaining 1950 */ 1951 public StrBuilder replaceFirst(final char search, final char replace) { 1952 if (search != replace) { 1953 for (int i = 0; i < size; i++) { 1954 if (buffer[i] == search) { 1955 buffer[i] = replace; 1956 break; 1957 } 1958 } 1959 } 1960 return this; 1961 } 1962 1963 //----------------------------------------------------------------------- 1964 /** 1965 * Replaces the search string with the replace string throughout the builder. 1966 * 1967 * @param searchStr the search string, null causes no action to occur 1968 * @param replaceStr the replace string, null is equivalent to an empty string 1969 * @return this, to enable chaining 1970 */ 1971 public StrBuilder replaceAll(final String searchStr, final String replaceStr) { 1972 final int searchLen = (searchStr == null ? 0 : searchStr.length()); 1973 if (searchLen > 0) { 1974 final int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); 1975 int index = indexOf(searchStr, 0); 1976 while (index >= 0) { 1977 replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen); 1978 index = indexOf(searchStr, index + replaceLen); 1979 } 1980 } 1981 return this; 1982 } 1983 1984 /** 1985 * Replaces the first instance of the search string with the replace string. 1986 * 1987 * @param searchStr the search string, null causes no action to occur 1988 * @param replaceStr the replace string, null is equivalent to an empty string 1989 * @return this, to enable chaining 1990 */ 1991 public StrBuilder replaceFirst(final String searchStr, final String replaceStr) { 1992 final int searchLen = (searchStr == null ? 0 : searchStr.length()); 1993 if (searchLen > 0) { 1994 final int index = indexOf(searchStr, 0); 1995 if (index >= 0) { 1996 final int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); 1997 replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen); 1998 } 1999 } 2000 return this; 2001 } 2002 2003 //----------------------------------------------------------------------- 2004 /** 2005 * Replaces all matches within the builder with the replace string. 2006 * <p> 2007 * Matchers can be used to perform advanced replace behaviour. 2008 * For example you could write a matcher to replace all occurrences 2009 * where the character 'a' is followed by a number. 2010 * 2011 * @param matcher the matcher to use to find the deletion, null causes no action 2012 * @param replaceStr the replace string, null is equivalent to an empty string 2013 * @return this, to enable chaining 2014 */ 2015 public StrBuilder replaceAll(final StrMatcher matcher, final String replaceStr) { 2016 return replace(matcher, replaceStr, 0, size, -1); 2017 } 2018 2019 /** 2020 * Replaces the first match within the builder with the replace string. 2021 * <p> 2022 * Matchers can be used to perform advanced replace behaviour. 2023 * For example you could write a matcher to replace 2024 * where the character 'a' is followed by a number. 2025 * 2026 * @param matcher the matcher to use to find the deletion, null causes no action 2027 * @param replaceStr the replace string, null is equivalent to an empty string 2028 * @return this, to enable chaining 2029 */ 2030 public StrBuilder replaceFirst(final StrMatcher matcher, final String replaceStr) { 2031 return replace(matcher, replaceStr, 0, size, 1); 2032 } 2033 2034 // ----------------------------------------------------------------------- 2035 /** 2036 * Advanced search and replaces within the builder using a matcher. 2037 * <p> 2038 * Matchers can be used to perform advanced behaviour. 2039 * For example you could write a matcher to delete all occurrences 2040 * where the character 'a' is followed by a number. 2041 * 2042 * @param matcher the matcher to use to find the deletion, null causes no action 2043 * @param replaceStr the string to replace the match with, null is a delete 2044 * @param startIndex the start index, inclusive, must be valid 2045 * @param endIndex the end index, exclusive, must be valid except 2046 * that if too large it is treated as end of string 2047 * @param replaceCount the number of times to replace, -1 for replace all 2048 * @return this, to enable chaining 2049 * @throws IndexOutOfBoundsException if start index is invalid 2050 */ 2051 public StrBuilder replace( 2052 final StrMatcher matcher, final String replaceStr, 2053 final int startIndex, int endIndex, final int replaceCount) { 2054 endIndex = validateRange(startIndex, endIndex); 2055 return replaceImpl(matcher, replaceStr, startIndex, endIndex, replaceCount); 2056 } 2057 2058 /** 2059 * Replaces within the builder using a matcher. 2060 * <p> 2061 * Matchers can be used to perform advanced behaviour. 2062 * For example you could write a matcher to delete all occurrences 2063 * where the character 'a' is followed by a number. 2064 * 2065 * @param matcher the matcher to use to find the deletion, null causes no action 2066 * @param replaceStr the string to replace the match with, null is a delete 2067 * @param from the start index, must be valid 2068 * @param to the end index (exclusive), must be valid 2069 * @param replaceCount the number of times to replace, -1 for replace all 2070 * @return this, to enable chaining 2071 * @throws IndexOutOfBoundsException if any index is invalid 2072 */ 2073 private StrBuilder replaceImpl( 2074 final StrMatcher matcher, final String replaceStr, 2075 final int from, int to, int replaceCount) { 2076 if (matcher == null || size == 0) { 2077 return this; 2078 } 2079 final int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); 2080 for (int i = from; i < to && replaceCount != 0; i++) { 2081 final char[] buf = buffer; 2082 final int removeLen = matcher.isMatch(buf, i, from, to); 2083 if (removeLen > 0) { 2084 replaceImpl(i, i + removeLen, removeLen, replaceStr, replaceLen); 2085 to = to - removeLen + replaceLen; 2086 i = i + replaceLen - 1; 2087 if (replaceCount > 0) { 2088 replaceCount--; 2089 } 2090 } 2091 } 2092 return this; 2093 } 2094 2095 //----------------------------------------------------------------------- 2096 /** 2097 * Reverses the string builder placing each character in the opposite index. 2098 * 2099 * @return this, to enable chaining 2100 */ 2101 public StrBuilder reverse() { 2102 if (size == 0) { 2103 return this; 2104 } 2105 2106 final int half = size / 2; 2107 final char[] buf = buffer; 2108 for (int leftIdx = 0, rightIdx = size - 1; leftIdx < half; leftIdx++, rightIdx--) { 2109 final char swap = buf[leftIdx]; 2110 buf[leftIdx] = buf[rightIdx]; 2111 buf[rightIdx] = swap; 2112 } 2113 return this; 2114 } 2115 2116 //----------------------------------------------------------------------- 2117 /** 2118 * Trims the builder by removing characters less than or equal to a space 2119 * from the beginning and end. 2120 * 2121 * @return this, to enable chaining 2122 */ 2123 public StrBuilder trim() { 2124 if (size == 0) { 2125 return this; 2126 } 2127 int len = size; 2128 final char[] buf = buffer; 2129 int pos = 0; 2130 while (pos < len && buf[pos] <= ' ') { 2131 pos++; 2132 } 2133 while (pos < len && buf[len - 1] <= ' ') { 2134 len--; 2135 } 2136 if (len < size) { 2137 delete(len, size); 2138 } 2139 if (pos > 0) { 2140 delete(0, pos); 2141 } 2142 return this; 2143 } 2144 2145 //----------------------------------------------------------------------- 2146 /** 2147 * Checks whether this builder starts with the specified string. 2148 * <p> 2149 * Note that this method handles null input quietly, unlike String. 2150 * 2151 * @param str the string to search for, null returns false 2152 * @return true if the builder starts with the string 2153 */ 2154 public boolean startsWith(final String str) { 2155 if (str == null) { 2156 return false; 2157 } 2158 final int len = str.length(); 2159 if (len == 0) { 2160 return true; 2161 } 2162 if (len > size) { 2163 return false; 2164 } 2165 for (int i = 0; i < len; i++) { 2166 if (buffer[i] != str.charAt(i)) { 2167 return false; 2168 } 2169 } 2170 return true; 2171 } 2172 2173 /** 2174 * Checks whether this builder ends with the specified string. 2175 * <p> 2176 * Note that this method handles null input quietly, unlike String. 2177 * 2178 * @param str the string to search for, null returns false 2179 * @return true if the builder ends with the string 2180 */ 2181 public boolean endsWith(final String str) { 2182 if (str == null) { 2183 return false; 2184 } 2185 final int len = str.length(); 2186 if (len == 0) { 2187 return true; 2188 } 2189 if (len > size) { 2190 return false; 2191 } 2192 int pos = size - len; 2193 for (int i = 0; i < len; i++, pos++) { 2194 if (buffer[pos] != str.charAt(i)) { 2195 return false; 2196 } 2197 } 2198 return true; 2199 } 2200 2201 //----------------------------------------------------------------------- 2202 /** 2203 * {@inheritDoc} 2204 */ 2205 @Override 2206 public CharSequence subSequence(final int startIndex, final int endIndex) { 2207 if (startIndex < 0) { 2208 throw new StringIndexOutOfBoundsException(startIndex); 2209 } 2210 if (endIndex > size) { 2211 throw new StringIndexOutOfBoundsException(endIndex); 2212 } 2213 if (startIndex > endIndex) { 2214 throw new StringIndexOutOfBoundsException(endIndex - startIndex); 2215 } 2216 return substring(startIndex, endIndex); 2217 } 2218 2219 /** 2220 * Extracts a portion of this string builder as a string. 2221 * 2222 * @param start the start index, inclusive, must be valid 2223 * @return the new string 2224 * @throws IndexOutOfBoundsException if the index is invalid 2225 */ 2226 public String substring(final int start) { 2227 return substring(start, size); 2228 } 2229 2230 /** 2231 * Extracts a portion of this string builder as a string. 2232 * <p> 2233 * Note: This method treats an endIndex greater than the length of the 2234 * builder as equal to the length of the builder, and continues 2235 * without error, unlike StringBuffer or String. 2236 * 2237 * @param startIndex the start index, inclusive, must be valid 2238 * @param endIndex the end index, exclusive, must be valid except 2239 * that if too large it is treated as end of string 2240 * @return the new string 2241 * @throws IndexOutOfBoundsException if the index is invalid 2242 */ 2243 public String substring(final int startIndex, int endIndex) { 2244 endIndex = validateRange(startIndex, endIndex); 2245 return new String(buffer, startIndex, endIndex - startIndex); 2246 } 2247 2248 /** 2249 * Extracts the leftmost characters from the string builder without 2250 * throwing an exception. 2251 * <p> 2252 * This method extracts the left <code>length</code> characters from 2253 * the builder. If this many characters are not available, the whole 2254 * builder is returned. Thus the returned string may be shorter than the 2255 * length requested. 2256 * 2257 * @param length the number of characters to extract, negative returns empty string 2258 * @return the new string 2259 */ 2260 public String leftString(final int length) { 2261 if (length <= 0) { 2262 return ""; 2263 } else if (length >= size) { 2264 return new String(buffer, 0, size); 2265 } else { 2266 return new String(buffer, 0, length); 2267 } 2268 } 2269 2270 /** 2271 * Extracts the rightmost characters from the string builder without 2272 * throwing an exception. 2273 * <p> 2274 * This method extracts the right <code>length</code> characters from 2275 * the builder. If this many characters are not available, the whole 2276 * builder is returned. Thus the returned string may be shorter than the 2277 * length requested. 2278 * 2279 * @param length the number of characters to extract, negative returns empty string 2280 * @return the new string 2281 */ 2282 public String rightString(final int length) { 2283 if (length <= 0) { 2284 return ""; 2285 } else if (length >= size) { 2286 return new String(buffer, 0, size); 2287 } else { 2288 return new String(buffer, size - length, length); 2289 } 2290 } 2291 2292 /** 2293 * Extracts some characters from the middle of the string builder without 2294 * throwing an exception. 2295 * <p> 2296 * This method extracts <code>length</code> characters from the builder 2297 * at the specified index. 2298 * If the index is negative it is treated as zero. 2299 * If the index is greater than the builder size, it is treated as the builder size. 2300 * If the length is negative, the empty string is returned. 2301 * If insufficient characters are available in the builder, as much as possible is returned. 2302 * Thus the returned string may be shorter than the length requested. 2303 * 2304 * @param index the index to start at, negative means zero 2305 * @param length the number of characters to extract, negative returns empty string 2306 * @return the new string 2307 */ 2308 public String midString(int index, final int length) { 2309 if (index < 0) { 2310 index = 0; 2311 } 2312 if (length <= 0 || index >= size) { 2313 return ""; 2314 } 2315 if (size <= index + length) { 2316 return new String(buffer, index, size - index); 2317 } 2318 return new String(buffer, index, length); 2319 } 2320 2321 //----------------------------------------------------------------------- 2322 /** 2323 * Checks if the string builder contains the specified char. 2324 * 2325 * @param ch the character to find 2326 * @return true if the builder contains the character 2327 */ 2328 public boolean contains(final char ch) { 2329 final char[] thisBuf = buffer; 2330 for (int i = 0; i < this.size; i++) { 2331 if (thisBuf[i] == ch) { 2332 return true; 2333 } 2334 } 2335 return false; 2336 } 2337 2338 /** 2339 * Checks if the string builder contains the specified string. 2340 * 2341 * @param str the string to find 2342 * @return true if the builder contains the string 2343 */ 2344 public boolean contains(final String str) { 2345 return indexOf(str, 0) >= 0; 2346 } 2347 2348 /** 2349 * Checks if the string builder contains a string matched using the 2350 * specified matcher. 2351 * <p> 2352 * Matchers can be used to perform advanced searching behaviour. 2353 * For example you could write a matcher to search for the character 2354 * 'a' followed by a number. 2355 * 2356 * @param matcher the matcher to use, null returns -1 2357 * @return true if the matcher finds a match in the builder 2358 */ 2359 public boolean contains(final StrMatcher matcher) { 2360 return indexOf(matcher, 0) >= 0; 2361 } 2362 2363 //----------------------------------------------------------------------- 2364 /** 2365 * Searches the string builder to find the first reference to the specified char. 2366 * 2367 * @param ch the character to find 2368 * @return the first index of the character, or -1 if not found 2369 */ 2370 public int indexOf(final char ch) { 2371 return indexOf(ch, 0); 2372 } 2373 2374 /** 2375 * Searches the string builder to find the first reference to the specified char. 2376 * 2377 * @param ch the character to find 2378 * @param startIndex the index to start at, invalid index rounded to edge 2379 * @return the first index of the character, or -1 if not found 2380 */ 2381 public int indexOf(final char ch, int startIndex) { 2382 startIndex = (startIndex < 0 ? 0 : startIndex); 2383 if (startIndex >= size) { 2384 return -1; 2385 } 2386 final char[] thisBuf = buffer; 2387 for (int i = startIndex; i < size; i++) { 2388 if (thisBuf[i] == ch) { 2389 return i; 2390 } 2391 } 2392 return -1; 2393 } 2394 2395 /** 2396 * Searches the string builder to find the first reference to the specified string. 2397 * <p> 2398 * Note that a null input string will return -1, whereas the JDK throws an exception. 2399 * 2400 * @param str the string to find, null returns -1 2401 * @return the first index of the string, or -1 if not found 2402 */ 2403 public int indexOf(final String str) { 2404 return indexOf(str, 0); 2405 } 2406 2407 /** 2408 * Searches the string builder to find the first reference to the specified 2409 * string starting searching from the given index. 2410 * <p> 2411 * Note that a null input string will return -1, whereas the JDK throws an exception. 2412 * 2413 * @param str the string to find, null returns -1 2414 * @param startIndex the index to start at, invalid index rounded to edge 2415 * @return the first index of the string, or -1 if not found 2416 */ 2417 public int indexOf(final String str, int startIndex) { 2418 startIndex = (startIndex < 0 ? 0 : startIndex); 2419 if (str == null || startIndex >= size) { 2420 return -1; 2421 } 2422 final int strLen = str.length(); 2423 if (strLen == 1) { 2424 return indexOf(str.charAt(0), startIndex); 2425 } 2426 if (strLen == 0) { 2427 return startIndex; 2428 } 2429 if (strLen > size) { 2430 return -1; 2431 } 2432 final char[] thisBuf = buffer; 2433 final int len = size - strLen + 1; 2434 outer: 2435 for (int i = startIndex; i < len; i++) { 2436 for (int j = 0; j < strLen; j++) { 2437 if (str.charAt(j) != thisBuf[i + j]) { 2438 continue outer; 2439 } 2440 } 2441 return i; 2442 } 2443 return -1; 2444 } 2445 2446 /** 2447 * Searches the string builder using the matcher to find the first match. 2448 * <p> 2449 * Matchers can be used to perform advanced searching behaviour. 2450 * For example you could write a matcher to find the character 'a' 2451 * followed by a number. 2452 * 2453 * @param matcher the matcher to use, null returns -1 2454 * @return the first index matched, or -1 if not found 2455 */ 2456 public int indexOf(final StrMatcher matcher) { 2457 return indexOf(matcher, 0); 2458 } 2459 2460 /** 2461 * Searches the string builder using the matcher to find the first 2462 * match searching from the given index. 2463 * <p> 2464 * Matchers can be used to perform advanced searching behaviour. 2465 * For example you could write a matcher to find the character 'a' 2466 * followed by a number. 2467 * 2468 * @param matcher the matcher to use, null returns -1 2469 * @param startIndex the index to start at, invalid index rounded to edge 2470 * @return the first index matched, or -1 if not found 2471 */ 2472 public int indexOf(final StrMatcher matcher, int startIndex) { 2473 startIndex = (startIndex < 0 ? 0 : startIndex); 2474 if (matcher == null || startIndex >= size) { 2475 return -1; 2476 } 2477 final int len = size; 2478 final char[] buf = buffer; 2479 for (int i = startIndex; i < len; i++) { 2480 if (matcher.isMatch(buf, i, startIndex, len) > 0) { 2481 return i; 2482 } 2483 } 2484 return -1; 2485 } 2486 2487 //----------------------------------------------------------------------- 2488 /** 2489 * Searches the string builder to find the last reference to the specified char. 2490 * 2491 * @param ch the character to find 2492 * @return the last index of the character, or -1 if not found 2493 */ 2494 public int lastIndexOf(final char ch) { 2495 return lastIndexOf(ch, size - 1); 2496 } 2497 2498 /** 2499 * Searches the string builder to find the last reference to the specified char. 2500 * 2501 * @param ch the character to find 2502 * @param startIndex the index to start at, invalid index rounded to edge 2503 * @return the last index of the character, or -1 if not found 2504 */ 2505 public int lastIndexOf(final char ch, int startIndex) { 2506 startIndex = (startIndex >= size ? size - 1 : startIndex); 2507 if (startIndex < 0) { 2508 return -1; 2509 } 2510 for (int i = startIndex; i >= 0; i--) { 2511 if (buffer[i] == ch) { 2512 return i; 2513 } 2514 } 2515 return -1; 2516 } 2517 2518 /** 2519 * Searches the string builder to find the last reference to the specified string. 2520 * <p> 2521 * Note that a null input string will return -1, whereas the JDK throws an exception. 2522 * 2523 * @param str the string to find, null returns -1 2524 * @return the last index of the string, or -1 if not found 2525 */ 2526 public int lastIndexOf(final String str) { 2527 return lastIndexOf(str, size - 1); 2528 } 2529 2530 /** 2531 * Searches the string builder to find the last reference to the specified 2532 * string starting searching from the given index. 2533 * <p> 2534 * Note that a null input string will return -1, whereas the JDK throws an exception. 2535 * 2536 * @param str the string to find, null returns -1 2537 * @param startIndex the index to start at, invalid index rounded to edge 2538 * @return the last index of the string, or -1 if not found 2539 */ 2540 public int lastIndexOf(final String str, int startIndex) { 2541 startIndex = (startIndex >= size ? size - 1 : startIndex); 2542 if (str == null || startIndex < 0) { 2543 return -1; 2544 } 2545 final int strLen = str.length(); 2546 if (strLen > 0 && strLen <= size) { 2547 if (strLen == 1) { 2548 return lastIndexOf(str.charAt(0), startIndex); 2549 } 2550 2551 outer: 2552 for (int i = startIndex - strLen + 1; i >= 0; i--) { 2553 for (int j = 0; j < strLen; j++) { 2554 if (str.charAt(j) != buffer[i + j]) { 2555 continue outer; 2556 } 2557 } 2558 return i; 2559 } 2560 2561 } else if (strLen == 0) { 2562 return startIndex; 2563 } 2564 return -1; 2565 } 2566 2567 /** 2568 * Searches the string builder using the matcher to find the last match. 2569 * <p> 2570 * Matchers can be used to perform advanced searching behaviour. 2571 * For example you could write a matcher to find the character 'a' 2572 * followed by a number. 2573 * 2574 * @param matcher the matcher to use, null returns -1 2575 * @return the last index matched, or -1 if not found 2576 */ 2577 public int lastIndexOf(final StrMatcher matcher) { 2578 return lastIndexOf(matcher, size); 2579 } 2580 2581 /** 2582 * Searches the string builder using the matcher to find the last 2583 * match searching from the given index. 2584 * <p> 2585 * Matchers can be used to perform advanced searching behaviour. 2586 * For example you could write a matcher to find the character 'a' 2587 * followed by a number. 2588 * 2589 * @param matcher the matcher to use, null returns -1 2590 * @param startIndex the index to start at, invalid index rounded to edge 2591 * @return the last index matched, or -1 if not found 2592 */ 2593 public int lastIndexOf(final StrMatcher matcher, int startIndex) { 2594 startIndex = (startIndex >= size ? size - 1 : startIndex); 2595 if (matcher == null || startIndex < 0) { 2596 return -1; 2597 } 2598 final char[] buf = buffer; 2599 final int endIndex = startIndex + 1; 2600 for (int i = startIndex; i >= 0; i--) { 2601 if (matcher.isMatch(buf, i, 0, endIndex) > 0) { 2602 return i; 2603 } 2604 } 2605 return -1; 2606 } 2607 2608 //----------------------------------------------------------------------- 2609 /** 2610 * Creates a tokenizer that can tokenize the contents of this builder. 2611 * <p> 2612 * This method allows the contents of this builder to be tokenized. 2613 * The tokenizer will be setup by default to tokenize on space, tab, 2614 * newline and formfeed (as per StringTokenizer). These values can be 2615 * changed on the tokenizer class, before retrieving the tokens. 2616 * <p> 2617 * The returned tokenizer is linked to this builder. You may intermix 2618 * calls to the builder and tokenizer within certain limits, however 2619 * there is no synchronization. Once the tokenizer has been used once, 2620 * it must be {@link StrTokenizer#reset() reset} to pickup the latest 2621 * changes in the builder. For example: 2622 * <pre> 2623 * StrBuilder b = new StrBuilder(); 2624 * b.append("a b "); 2625 * StrTokenizer t = b.asTokenizer(); 2626 * String[] tokens1 = t.getTokenArray(); // returns a,b 2627 * b.append("c d "); 2628 * String[] tokens2 = t.getTokenArray(); // returns a,b (c and d ignored) 2629 * t.reset(); // reset causes builder changes to be picked up 2630 * String[] tokens3 = t.getTokenArray(); // returns a,b,c,d 2631 * </pre> 2632 * In addition to simply intermixing appends and tokenization, you can also 2633 * call the set methods on the tokenizer to alter how it tokenizes. Just 2634 * remember to call reset when you want to pickup builder changes. 2635 * <p> 2636 * Calling {@link StrTokenizer#reset(String)} or {@link StrTokenizer#reset(char[])} 2637 * with a non-null value will break the link with the builder. 2638 * 2639 * @return a tokenizer that is linked to this builder 2640 */ 2641 public StrTokenizer asTokenizer() { 2642 return new StrBuilderTokenizer(); 2643 } 2644 2645 //----------------------------------------------------------------------- 2646 /** 2647 * Gets the contents of this builder as a Reader. 2648 * <p> 2649 * This method allows the contents of the builder to be read 2650 * using any standard method that expects a Reader. 2651 * <p> 2652 * To use, simply create a <code>StrBuilder</code>, populate it with 2653 * data, call <code>asReader</code>, and then read away. 2654 * <p> 2655 * The internal character array is shared between the builder and the reader. 2656 * This allows you to append to the builder after creating the reader, 2657 * and the changes will be picked up. 2658 * Note however, that no synchronization occurs, so you must perform 2659 * all operations with the builder and the reader in one thread. 2660 * <p> 2661 * The returned reader supports marking, and ignores the flush method. 2662 * 2663 * @return a reader that reads from this builder 2664 */ 2665 public Reader asReader() { 2666 return new StrBuilderReader(); 2667 } 2668 2669 //----------------------------------------------------------------------- 2670 /** 2671 * Gets this builder as a Writer that can be written to. 2672 * <p> 2673 * This method allows you to populate the contents of the builder 2674 * using any standard method that takes a Writer. 2675 * <p> 2676 * To use, simply create a <code>StrBuilder</code>, 2677 * call <code>asWriter</code>, and populate away. The data is available 2678 * at any time using the methods of the <code>StrBuilder</code>. 2679 * <p> 2680 * The internal character array is shared between the builder and the writer. 2681 * This allows you to intermix calls that append to the builder and 2682 * write using the writer and the changes will be occur correctly. 2683 * Note however, that no synchronization occurs, so you must perform 2684 * all operations with the builder and the writer in one thread. 2685 * <p> 2686 * The returned writer ignores the close and flush methods. 2687 * 2688 * @return a writer that populates this builder 2689 */ 2690 public Writer asWriter() { 2691 return new StrBuilderWriter(); 2692 } 2693 2694 /** 2695 * Appends current contents of this <code>StrBuilder</code> to the 2696 * provided {@link Appendable}. 2697 * <p> 2698 * This method tries to avoid doing any extra copies of contents. 2699 * 2700 * @param appendable the appendable to append data to 2701 * @throws IOException if an I/O error occurs 2702 * 2703 * @see #readFrom(Readable) 2704 */ 2705 public void appendTo(final Appendable appendable) throws IOException { 2706 if (appendable instanceof Writer) { 2707 ((Writer) appendable).write(buffer, 0, size); 2708 } else if (appendable instanceof StringBuilder) { 2709 ((StringBuilder) appendable).append(buffer, 0, size); 2710 } else if (appendable instanceof StringBuffer) { 2711 ((StringBuffer) appendable).append(buffer, 0, size); 2712 } else if (appendable instanceof CharBuffer) { 2713 ((CharBuffer) appendable).put(buffer, 0, size); 2714 } else { 2715 appendable.append(this); 2716 } 2717 } 2718 2719 /** 2720 * Checks the contents of this builder against another to see if they 2721 * contain the same character content ignoring case. 2722 * 2723 * @param other the object to check, null returns false 2724 * @return true if the builders contain the same characters in the same order 2725 */ 2726 public boolean equalsIgnoreCase(final StrBuilder other) { 2727 if (this == other) { 2728 return true; 2729 } 2730 if (this.size != other.size) { 2731 return false; 2732 } 2733 final char[] thisBuf = this.buffer; 2734 final char[] otherBuf = other.buffer; 2735 for (int i = size - 1; i >= 0; i--) { 2736 final char c1 = thisBuf[i]; 2737 final char c2 = otherBuf[i]; 2738 if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) { 2739 return false; 2740 } 2741 } 2742 return true; 2743 } 2744 2745 /** 2746 * Checks the contents of this builder against another to see if they 2747 * contain the same character content. 2748 * 2749 * @param other the object to check, null returns false 2750 * @return true if the builders contain the same characters in the same order 2751 */ 2752 public boolean equals(final StrBuilder other) { 2753 if (this == other) { 2754 return true; 2755 } 2756 if (other == null) { 2757 return false; 2758 } 2759 if (this.size != other.size) { 2760 return false; 2761 } 2762 final char[] thisBuf = this.buffer; 2763 final char[] otherBuf = other.buffer; 2764 for (int i = size - 1; i >= 0; i--) { 2765 if (thisBuf[i] != otherBuf[i]) { 2766 return false; 2767 } 2768 } 2769 return true; 2770 } 2771 2772 /** 2773 * Checks the contents of this builder against another to see if they 2774 * contain the same character content. 2775 * 2776 * @param obj the object to check, null returns false 2777 * @return true if the builders contain the same characters in the same order 2778 */ 2779 @Override 2780 public boolean equals(final Object obj) { 2781 return obj instanceof StrBuilder 2782 && equals((StrBuilder) obj); 2783 } 2784 2785 /** 2786 * Gets a suitable hash code for this builder. 2787 * 2788 * @return a hash code 2789 */ 2790 @Override 2791 public int hashCode() { 2792 final char[] buf = buffer; 2793 int hash = 0; 2794 for (int i = size - 1; i >= 0; i--) { 2795 hash = 31 * hash + buf[i]; 2796 } 2797 return hash; 2798 } 2799 2800 //----------------------------------------------------------------------- 2801 /** 2802 * Gets a String version of the string builder, creating a new instance 2803 * each time the method is called. 2804 * <p> 2805 * Note that unlike StringBuffer, the string version returned is 2806 * independent of the string builder. 2807 * 2808 * @return the builder as a String 2809 */ 2810 @Override 2811 public String toString() { 2812 return new String(buffer, 0, size); 2813 } 2814 2815 /** 2816 * Gets a StringBuffer version of the string builder, creating a 2817 * new instance each time the method is called. 2818 * 2819 * @return the builder as a StringBuffer 2820 */ 2821 public StringBuffer toStringBuffer() { 2822 return new StringBuffer(size).append(buffer, 0, size); 2823 } 2824 2825 /** 2826 * Gets a StringBuilder version of the string builder, creating a 2827 * new instance each time the method is called. 2828 * 2829 * @return the builder as a StringBuilder 2830 */ 2831 public StringBuilder toStringBuilder() { 2832 return new StringBuilder(size).append(buffer, 0, size); 2833 } 2834 2835 /** 2836 * Implement the {@link Builder} interface. 2837 * @return the builder as a String 2838 * @see #toString() 2839 */ 2840 @Override 2841 public String build() { 2842 return toString(); 2843 } 2844 2845 //----------------------------------------------------------------------- 2846 /** 2847 * Validates parameters defining a range of the builder. 2848 * 2849 * @param startIndex the start index, inclusive, must be valid 2850 * @param endIndex the end index, exclusive, must be valid except 2851 * that if too large it is treated as end of string 2852 * @return the new string 2853 * @throws IndexOutOfBoundsException if the index is invalid 2854 */ 2855 protected int validateRange(final int startIndex, int endIndex) { 2856 if (startIndex < 0) { 2857 throw new StringIndexOutOfBoundsException(startIndex); 2858 } 2859 if (endIndex > size) { 2860 endIndex = size; 2861 } 2862 if (startIndex > endIndex) { 2863 throw new StringIndexOutOfBoundsException("end < start"); 2864 } 2865 return endIndex; 2866 } 2867 2868 /** 2869 * Validates parameters defining a single index in the builder. 2870 * 2871 * @param index the index, must be valid 2872 * @throws IndexOutOfBoundsException if the index is invalid 2873 */ 2874 protected void validateIndex(final int index) { 2875 if (index < 0 || index > size) { 2876 throw new StringIndexOutOfBoundsException(index); 2877 } 2878 } 2879 2880 //----------------------------------------------------------------------- 2881 /** 2882 * Inner class to allow StrBuilder to operate as a tokenizer. 2883 */ 2884 class StrBuilderTokenizer extends StrTokenizer { 2885 2886 /** 2887 * Default constructor. 2888 */ 2889 StrBuilderTokenizer() { 2890 super(); 2891 } 2892 2893 /** {@inheritDoc} */ 2894 @Override 2895 protected List<String> tokenize(final char[] chars, final int offset, final int count) { 2896 if (chars == null) { 2897 return super.tokenize( 2898 StrBuilder.this.buffer, 0, StrBuilder.this.size()); 2899 } 2900 return super.tokenize(chars, offset, count); 2901 } 2902 2903 /** {@inheritDoc} */ 2904 @Override 2905 public String getContent() { 2906 final String str = super.getContent(); 2907 if (str == null) { 2908 return StrBuilder.this.toString(); 2909 } 2910 return str; 2911 } 2912 } 2913 2914 //----------------------------------------------------------------------- 2915 /** 2916 * Inner class to allow StrBuilder to operate as a reader. 2917 */ 2918 class StrBuilderReader extends Reader { 2919 /** The current stream position. */ 2920 private int pos; 2921 /** The last mark position. */ 2922 private int mark; 2923 2924 /** 2925 * Default constructor. 2926 */ 2927 StrBuilderReader() { 2928 super(); 2929 } 2930 2931 /** {@inheritDoc} */ 2932 @Override 2933 public void close() { 2934 // do nothing 2935 } 2936 2937 /** {@inheritDoc} */ 2938 @Override 2939 public int read() { 2940 if (!ready()) { 2941 return -1; 2942 } 2943 return StrBuilder.this.charAt(pos++); 2944 } 2945 2946 /** {@inheritDoc} */ 2947 @Override 2948 public int read(final char[] b, final int off, int len) { 2949 if (off < 0 || len < 0 || off > b.length 2950 || (off + len) > b.length || (off + len) < 0) { 2951 throw new IndexOutOfBoundsException(); 2952 } 2953 if (len == 0) { 2954 return 0; 2955 } 2956 if (pos >= StrBuilder.this.size()) { 2957 return -1; 2958 } 2959 if (pos + len > size()) { 2960 len = StrBuilder.this.size() - pos; 2961 } 2962 StrBuilder.this.getChars(pos, pos + len, b, off); 2963 pos += len; 2964 return len; 2965 } 2966 2967 /** {@inheritDoc} */ 2968 @Override 2969 public long skip(long n) { 2970 if (pos + n > StrBuilder.this.size()) { 2971 n = StrBuilder.this.size() - pos; 2972 } 2973 if (n < 0) { 2974 return 0; 2975 } 2976 pos += n; 2977 return n; 2978 } 2979 2980 /** {@inheritDoc} */ 2981 @Override 2982 public boolean ready() { 2983 return pos < StrBuilder.this.size(); 2984 } 2985 2986 /** {@inheritDoc} */ 2987 @Override 2988 public boolean markSupported() { 2989 return true; 2990 } 2991 2992 /** {@inheritDoc} */ 2993 @Override 2994 public void mark(final int readAheadLimit) { 2995 mark = pos; 2996 } 2997 2998 /** {@inheritDoc} */ 2999 @Override 3000 public void reset() { 3001 pos = mark; 3002 } 3003 } 3004 3005 //----------------------------------------------------------------------- 3006 /** 3007 * Inner class to allow StrBuilder to operate as a writer. 3008 */ 3009 class StrBuilderWriter extends Writer { 3010 3011 /** 3012 * Default constructor. 3013 */ 3014 StrBuilderWriter() { 3015 super(); 3016 } 3017 3018 /** {@inheritDoc} */ 3019 @Override 3020 public void close() { 3021 // do nothing 3022 } 3023 3024 /** {@inheritDoc} */ 3025 @Override 3026 public void flush() { 3027 // do nothing 3028 } 3029 3030 /** {@inheritDoc} */ 3031 @Override 3032 public void write(final int c) { 3033 StrBuilder.this.append((char) c); 3034 } 3035 3036 /** {@inheritDoc} */ 3037 @Override 3038 public void write(final char[] cbuf) { 3039 StrBuilder.this.append(cbuf); 3040 } 3041 3042 /** {@inheritDoc} */ 3043 @Override 3044 public void write(final char[] cbuf, final int off, final int len) { 3045 StrBuilder.this.append(cbuf, off, len); 3046 } 3047 3048 /** {@inheritDoc} */ 3049 @Override 3050 public void write(final String str) { 3051 StrBuilder.this.append(str); 3052 } 3053 3054 /** {@inheritDoc} */ 3055 @Override 3056 public void write(final String str, final int off, final int len) { 3057 StrBuilder.this.append(str, off, len); 3058 } 3059 } 3060 3061}