forked from apache/commons-lang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringUtils.java
More file actions
9236 lines (8924 loc) · 385 KB
/
StringUtils.java
File metadata and controls
9236 lines (8924 loc) · 385 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3;
import java.io.UnsupportedEncodingException;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.function.Suppliers;
import org.apache.commons.lang3.stream.LangCollectors;
import org.apache.commons.lang3.stream.Streams;
/**
* Operations on {@link String} that are
* {@code null} safe.
*
* <ul>
* <li><strong>IsEmpty/IsBlank</strong>
* - checks if a String contains text</li>
* <li><strong>Trim/Strip</strong>
* - removes leading and trailing whitespace</li>
* <li><strong>Equals/Compare</strong>
* - compares two strings in a null-safe manner</li>
* <li><strong>startsWith</strong>
* - check if a String starts with a prefix in a null-safe manner</li>
* <li><strong>endsWith</strong>
* - check if a String ends with a suffix in a null-safe manner</li>
* <li><strong>IndexOf/LastIndexOf/Contains</strong>
* - null-safe index-of checks</li>
* <li><strong>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</strong>
* - index-of any of a set of Strings</li>
* <li><strong>ContainsOnly/ContainsNone/ContainsAny</strong>
* - checks if String contains only/none/any of these characters</li>
* <li><strong>Substring/Left/Right/Mid</strong>
* - null-safe substring extractions</li>
* <li><strong>SubstringBefore/SubstringAfter/SubstringBetween</strong>
* - substring extraction relative to other strings</li>
* <li><strong>Split/Join</strong>
* - splits a String into an array of substrings and vice versa</li>
* <li><strong>Remove/Delete</strong>
* - removes part of a String</li>
* <li><strong>Replace/Overlay</strong>
* - Searches a String and replaces one String with another</li>
* <li><strong>Chomp/Chop</strong>
* - removes the last part of a String</li>
* <li><strong>AppendIfMissing</strong>
* - appends a suffix to the end of the String if not present</li>
* <li><strong>PrependIfMissing</strong>
* - prepends a prefix to the start of the String if not present</li>
* <li><strong>LeftPad/RightPad/Center/Repeat</strong>
* - pads a String</li>
* <li><strong>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</strong>
* - changes the case of a String</li>
* <li><strong>CountMatches</strong>
* - counts the number of occurrences of one String in another</li>
* <li><strong>IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable</strong>
* - checks the characters in a String</li>
* <li><strong>DefaultString</strong>
* - protects against a null input String</li>
* <li><strong>Rotate</strong>
* - rotate (circular shift) a String</li>
* <li><strong>Reverse/ReverseDelimited</strong>
* - reverses a String</li>
* <li><strong>Abbreviate</strong>
* - abbreviates a string using ellipses or another given String</li>
* <li><strong>Difference</strong>
* - compares Strings and reports on their differences</li>
* <li><strong>LevenshteinDistance</strong>
* - the number of changes needed to change one String into another</li>
* </ul>
*
* <p>The {@link StringUtils} class defines certain words related to
* String handling.</p>
*
* <ul>
* <li>null - {@code null}</li>
* <li>empty - a zero-length string ({@code ""})</li>
* <li>space - the space character ({@code ' '}, char 32)</li>
* <li>whitespace - the characters defined by {@link Character#isWhitespace(char)}</li>
* <li>trim - the characters <= 32 as in {@link String#trim()}</li>
* </ul>
*
* <p>{@link StringUtils} handles {@code null} input Strings quietly.
* That is to say that a {@code null} input will return {@code null}.
* Where a {@code boolean} or {@code int} is being returned
* details vary by method.</p>
*
* <p>A side effect of the {@code null} handling is that a
* {@link NullPointerException} should be considered a bug in
* {@link StringUtils}.</p>
*
* <p>Methods in this class include sample code in their Javadoc comments to explain their operation.
* The symbol {@code *} is used to indicate any input including {@code null}.</p>
*
* <p>#ThreadSafe#</p>
*
* @see String
* @since 1.0
*/
//@Immutable
public class StringUtils {
// Performance testing notes (JDK 1.4, Jul03, scolebourne)
// Whitespace:
// Character.isWhitespace() is faster than WHITESPACE.indexOf()
// where WHITESPACE is a string of all whitespace characters
//
// Character access:
// String.charAt(n) versus toCharArray(), then array[n]
// String.charAt(n) is about 15% worse for a 10K string
// They are about equal for a length 50 string
// String.charAt(n) is about 4 times better for a length 3 string
// String.charAt(n) is best bet overall
//
// Append:
// String.concat about twice as fast as StringBuffer.append
// (not sure who tested this)
/**
* This is a 3 character version of an ellipsis. There is a Unicode character for a HORIZONTAL ELLIPSIS, U+2026 '…', this isn't it.
*/
private static final String ELLIPSIS3 = "...";
/**
* A String for a space character.
*
* @since 3.2
*/
public static final String SPACE = " ";
/**
* The empty String {@code ""}.
*
* @since 2.0
*/
public static final String EMPTY = "";
/**
* The null String {@code null}. Package-private only.
*/
static final String NULL = null;
/**
* A String for linefeed LF ("\n").
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
* for Character and String Literals</a>
* @since 3.2
*/
public static final String LF = "\n";
/**
* A String for carriage return CR ("\r").
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
* for Character and String Literals</a>
* @since 3.2
*/
public static final String CR = "\r";
/**
* Represents a failed index search.
*
* @since 2.1
*/
public static final int INDEX_NOT_FOUND = -1;
/**
* The maximum size to which the padding constant(s) can expand.
*/
private static final int PAD_LIMIT = 8192;
/**
* The default maximum depth at which recursive replacement will continue until no further search replacements are possible.
*/
private static final int DEFAULT_TTL = 5;
/**
* Pattern used in {@link #stripAccents(String)}.
*/
private static final Pattern STRIP_ACCENTS_PATTERN = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); //$NON-NLS-1$
/**
* Abbreviates a String using ellipses. This will convert "Now is the time for all good men" into "Now is the time for..."
*
* <p>
* Specifically:
* </p>
* <ul>
* <li>If the number of characters in {@code str} is less than or equal to {@code maxWidth}, return {@code str}.</li>
* <li>Else abbreviate it to {@code (substring(str, 0, max - 3) + "...")}.</li>
* <li>If {@code maxWidth} is less than {@code 4}, throw an {@link IllegalArgumentException}.</li>
* <li>In no case will it return a String of length greater than {@code maxWidth}.</li>
* </ul>
*
* <pre>
* StringUtils.abbreviate(null, *) = null
* StringUtils.abbreviate("", 4) = ""
* StringUtils.abbreviate("abcdefg", 6) = "abc..."
* StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 4) = "a..."
* StringUtils.abbreviate("abcdefg", 3) = Throws {@link IllegalArgumentException}.
* </pre>
*
* @param str the String to check, may be null.
* @param maxWidth maximum length of result String, must be at least 4.
* @return abbreviated String, {@code null} if null String input.
* @throws IllegalArgumentException if the width is too small.
* @since 2.0
*/
public static String abbreviate(final String str, final int maxWidth) {
return abbreviate(str, ELLIPSIS3, 0, maxWidth);
}
/**
* Abbreviates a String using ellipses. This will convert "Now is the time for all good men" into "...is the time for...".
*
* <p>
* Works like {@code abbreviate(String, int)}, but allows you to specify a "left edge" offset. Note that this left edge is not necessarily going to be the
* leftmost character in the result, or the first character following the ellipses, but it will appear somewhere in the result.
* </p>
* <p>
* In no case will it return a String of length greater than {@code maxWidth}.
* </p>
*
* <pre>
* StringUtils.abbreviate(null, *, *) = null
* StringUtils.abbreviate("", 0, 4) = ""
* StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..."
* StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..."
* StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghij", 0, 3) = Throws {@link IllegalArgumentException}.
* StringUtils.abbreviate("abcdefghij", 5, 6) = Throws {@link IllegalArgumentException}.
* </pre>
*
* @param str the String to check, may be null.
* @param offset left edge of source String.
* @param maxWidth maximum length of result String, must be at least 4.
* @return abbreviated String, {@code null} if null String input.
* @throws IllegalArgumentException if the width is too small.
* @since 2.0
*/
public static String abbreviate(final String str, final int offset, final int maxWidth) {
return abbreviate(str, ELLIPSIS3, offset, maxWidth);
}
/**
* Abbreviates a String using another given String as replacement marker. This will convert "Now is the time for all good men" into "Now is the time for..."
* when "..." is the replacement marker.
*
* <p>
* Specifically:
* </p>
* <ul>
* <li>If the number of characters in {@code str} is less than or equal to {@code maxWidth}, return {@code str}.</li>
* <li>Else abbreviate it to {@code (substring(str, 0, max - abbrevMarker.length) + abbrevMarker)}.</li>
* <li>If {@code maxWidth} is less than {@code abbrevMarker.length + 1}, throw an {@link IllegalArgumentException}.</li>
* <li>In no case will it return a String of length greater than {@code maxWidth}.</li>
* </ul>
*
* <pre>
* StringUtils.abbreviate(null, "...", *) = null
* StringUtils.abbreviate("abcdefg", null, *) = "abcdefg"
* StringUtils.abbreviate("", "...", 4) = ""
* StringUtils.abbreviate("abcdefg", ".", 5) = "abcd."
* StringUtils.abbreviate("abcdefg", ".", 7) = "abcdefg"
* StringUtils.abbreviate("abcdefg", ".", 8) = "abcdefg"
* StringUtils.abbreviate("abcdefg", "..", 4) = "ab.."
* StringUtils.abbreviate("abcdefg", "..", 3) = "a.."
* StringUtils.abbreviate("abcdefg", "..", 2) = Throws {@link IllegalArgumentException}.
* StringUtils.abbreviate("abcdefg", "...", 3) = Throws {@link IllegalArgumentException}.
* </pre>
*
* @param str the String to check, may be null.
* @param abbrevMarker the String used as replacement marker.
* @param maxWidth maximum length of result String, must be at least {@code abbrevMarker.length + 1}.
* @return abbreviated String, {@code null} if null String input.
* @throws IllegalArgumentException if the width is too small.
* @since 3.6
*/
public static String abbreviate(final String str, final String abbrevMarker, final int maxWidth) {
return abbreviate(str, abbrevMarker, 0, maxWidth);
}
/**
* Abbreviates a String using a given replacement marker. This will convert "Now is the time for all good men" into "...is the time for..." when "..." is
* the replacement marker.
* <p>
* Works like {@code abbreviate(String, String, int)}, but allows you to specify a "left edge" offset. Note that this left edge is not necessarily going to
* be the leftmost character in the result, or the first character following the replacement marker, but it will appear somewhere in the result.
* </p>
* <p>
* In no case will it return a String of length greater than {@code maxWidth}.
* </p>
*
* <pre>
* StringUtils.abbreviate(null, null, *, *) = null
* StringUtils.abbreviate("abcdefghijklmno", null, *, *) = "abcdefghijklmno"
* StringUtils.abbreviate("", "...", 0, 4) = ""
* StringUtils.abbreviate("abcdefghijklmno", "---", -1, 10) = "abcdefg---"
* StringUtils.abbreviate("abcdefghijklmno", ",", 0, 10) = "abcdefghi,"
* StringUtils.abbreviate("abcdefghijklmno", ",", 1, 10) = "abcdefghi,"
* StringUtils.abbreviate("abcdefghijklmno", ",", 2, 10) = "abcdefghi,"
* StringUtils.abbreviate("abcdefghijklmno", "::", 4, 10) = "::efghij::"
* StringUtils.abbreviate("abcdefghijklmno", "...", 6, 10) = "...ghij..."
* StringUtils.abbreviate("abcdefghijklmno", "…", 6, 10) = "…ghij…"
* StringUtils.abbreviate("abcdefghijklmno", "*", 9, 10) = "*ghijklmno"
* StringUtils.abbreviate("abcdefghijklmno", "'", 10, 10) = "'ghijklmno"
* StringUtils.abbreviate("abcdefghijklmno", "!", 12, 10) = "!ghijklmno"
* StringUtils.abbreviate("abcdefghij", "abra", 0, 4) = Throws {@link IllegalArgumentException}.
* StringUtils.abbreviate("abcdefghij", "...", 5, 6) = Throws {@link IllegalArgumentException}.
* </pre>
*
* @param str the String to check, may be null.
* @param abbrevMarker the String used as replacement marker, for example "...", or Unicode HORIZONTAL ELLIPSIS, U+2026 '…'.
* @param offset left edge of source String.
* @param maxWidth maximum length of result String, must be at least 4.
* @return abbreviated String, {@code null} if null String input.
* @throws IllegalArgumentException if the width is too small.
* @since 3.6
*/
public static String abbreviate(final String str, String abbrevMarker, int offset, final int maxWidth) {
if (isEmpty(str)) {
return str;
}
if (abbrevMarker == null) {
abbrevMarker = EMPTY;
}
final int abbrevMarkerLength = abbrevMarker.length();
final int minAbbrevWidth = abbrevMarkerLength + 1;
final int minAbbrevWidthOffset = abbrevMarkerLength + abbrevMarkerLength + 1;
if (maxWidth < minAbbrevWidth) {
throw new IllegalArgumentException(String.format("Minimum abbreviation width is %d", minAbbrevWidth));
}
final int strLen = str.length();
if (strLen <= maxWidth) {
return str;
}
if (strLen - offset <= maxWidth - abbrevMarkerLength) {
return abbrevMarker + str.substring(strLen - (maxWidth - abbrevMarkerLength));
}
if (offset <= abbrevMarkerLength + 1) {
return str.substring(0, maxWidth - abbrevMarkerLength) + abbrevMarker;
}
if (maxWidth < minAbbrevWidthOffset) {
throw new IllegalArgumentException(String.format("Minimum abbreviation width with offset is %d", minAbbrevWidthOffset));
}
return abbrevMarker + abbreviate(str.substring(offset), abbrevMarker, maxWidth - abbrevMarkerLength);
}
/**
* Abbreviates a String to the length passed, replacing the middle characters with the supplied replacement String.
*
* <p>
* This abbreviation only occurs if the following criteria is met:
* </p>
* <ul>
* <li>Neither the String for abbreviation nor the replacement String are null or empty</li>
* <li>The length to truncate to is less than the length of the supplied String</li>
* <li>The length to truncate to is greater than 0</li>
* <li>The abbreviated String will have enough room for the length supplied replacement String and the first and last characters of the supplied String for
* abbreviation</li>
* </ul>
* <p>
* Otherwise, the returned String will be the same as the supplied String for abbreviation.
* </p>
*
* <pre>
* StringUtils.abbreviateMiddle(null, null, 0) = null
* StringUtils.abbreviateMiddle("abc", null, 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 3) = "abc"
* StringUtils.abbreviateMiddle("abcdef", ".", 4) = "ab.f"
* </pre>
*
* @param str the String to abbreviate, may be null.
* @param middle the String to replace the middle characters with, may be null.
* @param length the length to abbreviate {@code str} to.
* @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.
* @since 2.5
*/
public static String abbreviateMiddle(final String str, final String middle, final int length) {
if (isAnyEmpty(str, middle) || length >= str.length() || length < middle.length() + 2) {
return str;
}
final int targetString = length - middle.length();
final int startOffset = targetString / 2 + targetString % 2;
final int endOffset = str.length() - targetString / 2;
return str.substring(0, startOffset) + middle + str.substring(endOffset);
}
/**
* Appends the suffix to the end of the string if the string does not already end with any of the suffixes.
*
* <pre>
* StringUtils.appendIfMissing(null, null) = null
* StringUtils.appendIfMissing("abc", null) = "abc"
* StringUtils.appendIfMissing("", "xyz" = "xyz"
* StringUtils.appendIfMissing("abc", "xyz") = "abcxyz"
* StringUtils.appendIfMissing("abcxyz", "xyz") = "abcxyz"
* StringUtils.appendIfMissing("abcXYZ", "xyz") = "abcXYZxyz"
* </pre>
* <p>
* With additional suffixes,
* </p>
*
* <pre>
* StringUtils.appendIfMissing(null, null, null) = null
* StringUtils.appendIfMissing("abc", null, null) = "abc"
* StringUtils.appendIfMissing("", "xyz", null) = "xyz"
* StringUtils.appendIfMissing("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
* StringUtils.appendIfMissing("abc", "xyz", "") = "abc"
* StringUtils.appendIfMissing("abc", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissing("abcxyz", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissing("abcmno", "xyz", "mno") = "abcmno"
* StringUtils.appendIfMissing("abcXYZ", "xyz", "mno") = "abcXYZxyz"
* StringUtils.appendIfMissing("abcMNO", "xyz", "mno") = "abcMNOxyz"
* </pre>
*
* @param str The string.
* @param suffix The suffix to append to the end of the string.
* @param suffixes Additional suffixes that are valid terminators.
* @return A new String if suffix was appended, the same string otherwise.
* @since 3.2
* @deprecated Use {@link Strings#appendIfMissing(String, CharSequence, CharSequence...) Strings.CS.appendIfMissing(String, CharSequence, CharSequence...)}.
*/
@Deprecated
public static String appendIfMissing(final String str, final CharSequence suffix, final CharSequence... suffixes) {
return Strings.CS.appendIfMissing(str, suffix, suffixes);
}
/**
* Appends the suffix to the end of the string if the string does not
* already end, case-insensitive, with any of the suffixes.
*
* <pre>
* StringUtils.appendIfMissingIgnoreCase(null, null) = null
* StringUtils.appendIfMissingIgnoreCase("abc", null) = "abc"
* StringUtils.appendIfMissingIgnoreCase("", "xyz") = "xyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz") = "abcXYZ"
* </pre>
* <p>With additional suffixes,</p>
* <pre>
* StringUtils.appendIfMissingIgnoreCase(null, null, null) = null
* StringUtils.appendIfMissingIgnoreCase("abc", null, null) = "abc"
* StringUtils.appendIfMissingIgnoreCase("", "xyz", null) = "xyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "") = "abc"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno") = "abcmno"
* StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno") = "abcXYZ"
* StringUtils.appendIfMissingIgnoreCase("abcMNO", "xyz", "mno") = "abcMNO"
* </pre>
*
* @param str The string.
* @param suffix The suffix to append to the end of the string.
* @param suffixes Additional suffixes that are valid terminators.
* @return A new String if suffix was appended, the same string otherwise.
* @since 3.2
* @deprecated Use {@link Strings#appendIfMissing(String, CharSequence, CharSequence...) Strings.CI.appendIfMissing(String, CharSequence, CharSequence...)}.
*/
@Deprecated
public static String appendIfMissingIgnoreCase(final String str, final CharSequence suffix, final CharSequence... suffixes) {
return Strings.CI.appendIfMissing(str, suffix, suffixes);
}
/**
* Computes the capacity required for a StringBuilder to hold {@code items} of {@code maxElementChars} characters plus the separators between them. The
* separator is assumed to be 1 character.
*
* @param count The number of items.
* @param maxElementChars The maximum number of characters per item.
* @return A StringBuilder with the appropriate capacity.
*/
private static StringBuilder capacity(final int count, final byte maxElementChars) {
return new StringBuilder(count * maxElementChars + count - 1);
}
/**
* Capitalizes a String changing the first character to title case as per {@link Character#toTitleCase(int)}. No other characters are changed.
*
* <p>
* For a word based algorithm, see {@link org.apache.commons.text.WordUtils#capitalize(String)}. A {@code null} input String returns {@code null}.
* </p>
*
* <pre>
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
* StringUtils.capitalize("'cat'") = "'cat'"
* </pre>
*
* @param str the String to capitalize, may be null.
* @return the capitalized String, {@code null} if null String input.
* @see org.apache.commons.text.WordUtils#capitalize(String)
* @see #uncapitalize(String)
* @since 2.0
*/
public static String capitalize(final String str) {
if (isEmpty(str)) {
return str;
}
final int firstCodepoint = str.codePointAt(0);
final int newCodePoint = Character.toTitleCase(firstCodepoint);
if (firstCodepoint == newCodePoint) {
// already capitalized
return str;
}
final int[] newCodePoints = str.codePoints().toArray();
newCodePoints[0] = newCodePoint; // copy the first code point
return new String(newCodePoints, 0, newCodePoints.length);
}
/**
* Centers a String in a larger String of size {@code size} using the space character (' ').
*
* <p>
* If the size is less than the String length, the original String is returned. A {@code null} String returns {@code null}. A negative size is treated as
* zero.
* </p>
*
* <p>
* Equivalent to {@code center(str, size, " ")}.
* </p>
*
* <pre>
* StringUtils.center(null, *) = null
* StringUtils.center("", 4) = " "
* StringUtils.center("ab", -1) = "ab"
* StringUtils.center("ab", 4) = " ab "
* StringUtils.center("abcd", 2) = "abcd"
* StringUtils.center("a", 4) = " a "
* </pre>
*
* @param str the String to center, may be null.
* @param size the int size of new String, negative treated as zero.
* @return centered String, {@code null} if null String input.
*/
public static String center(final String str, final int size) {
return center(str, size, ' ');
}
/**
* Centers a String in a larger String of size {@code size}. Uses a supplied character as the value to pad the String with.
*
* <p>
* If the size is less than the String length, the String is returned. A {@code null} String returns {@code null}. A negative size is treated as zero.
* </p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, ' ') = " "
* StringUtils.center("ab", -1, ' ') = "ab"
* StringUtils.center("ab", 4, ' ') = " ab "
* StringUtils.center("abcd", 2, ' ') = "abcd"
* StringUtils.center("a", 4, ' ') = " a "
* StringUtils.center("a", 4, 'y') = "yayy"
* </pre>
*
* @param str the String to center, may be null.
* @param size the int size of new String, negative treated as zero.
* @param padChar the character to pad the new String with.
* @return centered String, {@code null} if null String input.
* @since 2.0
*/
public static String center(String str, final int size, final char padChar) {
if (str == null || size <= 0) {
return str;
}
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padChar);
return rightPad(str, size, padChar);
}
/**
* Centers a String in a larger String of size {@code size}. Uses a supplied String as the value to pad the String with.
*
* <p>
* If the size is less than the String length, the String is returned. A {@code null} String returns {@code null}. A negative size is treated as zero.
* </p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, " ") = " "
* StringUtils.center("ab", -1, " ") = "ab"
* StringUtils.center("ab", 4, " ") = " ab "
* StringUtils.center("abcd", 2, " ") = "abcd"
* StringUtils.center("a", 4, " ") = " a "
* StringUtils.center("a", 4, "yz") = "yayz"
* StringUtils.center("abc", 7, null) = " abc "
* StringUtils.center("abc", 7, "") = " abc "
* </pre>
*
* @param str the String to center, may be null.
* @param size the int size of new String, negative treated as zero.
* @param padStr the String to pad the new String with, must not be null or empty.
* @return centered String, {@code null} if null String input.
* @throws IllegalArgumentException if padStr is {@code null} or empty.
*/
public static String center(String str, final int size, String padStr) {
if (str == null || size <= 0) {
return str;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padStr);
return rightPad(str, size, padStr);
}
/**
* Removes one newline from end of a String if it's there, otherwise leave it alone. A newline is "{@code \n}", "{@code \r}", or
* "{@code \r\n}".
*
* <p>
* NOTE: This method changed in 2.0. It now more closely matches Perl chomp.
* </p>
*
* <pre>
* StringUtils.chomp(null) = null
* StringUtils.chomp("") = ""
* StringUtils.chomp("abc \r") = "abc "
* StringUtils.chomp("abc\n") = "abc"
* StringUtils.chomp("abc\r\n") = "abc"
* StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
* StringUtils.chomp("abc\n\r") = "abc\n"
* StringUtils.chomp("abc\n\rabc") = "abc\n\rabc"
* StringUtils.chomp("\r") = ""
* StringUtils.chomp("\n") = ""
* StringUtils.chomp("\r\n") = ""
* </pre>
*
* @param str the String to chomp a newline from, may be null.
* @return String without newline, {@code null} if null String input.
*/
public static String chomp(final String str) {
if (isEmpty(str)) {
return str;
}
if (str.length() == 1) {
final char ch = str.charAt(0);
if (ch == CharUtils.CR || ch == CharUtils.LF) {
return EMPTY;
}
return str;
}
int lastIdx = str.length() - 1;
final char last = str.charAt(lastIdx);
if (last == CharUtils.LF) {
if (str.charAt(lastIdx - 1) == CharUtils.CR) {
lastIdx--;
}
} else if (last != CharUtils.CR) {
lastIdx++;
}
return str.substring(0, lastIdx);
}
/**
* Removes {@code separator} from the end of {@code str} if it's there, otherwise leave it alone.
*
* <p>
* NOTE: This method changed in version 2.0. It now more closely matches Perl chomp. For the previous behavior, use
* {@link #substringBeforeLast(String, String)}. This method uses {@link String#endsWith(String)}.
* </p>
*
* <pre>
* StringUtils.chomp(null, *) = null
* StringUtils.chomp("", *) = ""
* StringUtils.chomp("foobar", "bar") = "foo"
* StringUtils.chomp("foobar", "baz") = "foobar"
* StringUtils.chomp("foo", "foo") = ""
* StringUtils.chomp("foo ", "foo") = "foo "
* StringUtils.chomp(" foo", "foo") = " "
* StringUtils.chomp("foo", "foooo") = "foo"
* StringUtils.chomp("foo", "") = "foo"
* StringUtils.chomp("foo", null) = "foo"
* </pre>
*
* @param str the String to chomp from, may be null.
* @param separator separator String, may be null.
* @return String without trailing separator, {@code null} if null String input.
* @deprecated This feature will be removed in Lang 4, use {@link StringUtils#removeEnd(String, String)} instead.
*/
@Deprecated
public static String chomp(final String str, final String separator) {
return Strings.CS.removeEnd(str, separator);
}
/**
* Removes the last character from a String.
*
* <p>
* If the String ends in {@code \r\n}, then remove both of them.
* </p>
*
* <pre>
* StringUtils.chop(null) = null
* StringUtils.chop("") = ""
* StringUtils.chop("abc \r") = "abc "
* StringUtils.chop("abc\n") = "abc"
* StringUtils.chop("abc\r\n") = "abc"
* StringUtils.chop("abc") = "ab"
* StringUtils.chop("abc\nabc") = "abc\nab"
* StringUtils.chop("a") = ""
* StringUtils.chop("\r") = ""
* StringUtils.chop("\n") = ""
* StringUtils.chop("\r\n") = ""
* </pre>
*
* @param str the String to chop last character from, may be null.
* @return String without last character, {@code null} if null String input.
*/
public static String chop(final String str) {
if (str == null) {
return null;
}
final int strLen = str.length();
if (strLen < 2) {
return EMPTY;
}
final int lastIdx = strLen - 1;
final String ret = str.substring(0, lastIdx);
final char last = str.charAt(lastIdx);
if (last == CharUtils.LF && ret.charAt(lastIdx - 1) == CharUtils.CR) {
return ret.substring(0, lastIdx - 1);
}
return ret;
}
/**
* Compares two Strings lexicographically, as per {@link String#compareTo(String)}, returning :
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>
* This is a {@code null} safe version of:
* </p>
*
* <pre>
* str1.compareTo(str2)
* </pre>
*
* <p>
* {@code null} value is considered less than non-{@code null} value. Two {@code null} references are considered equal.
* </p>
*
* <pre>{@code
* StringUtils.compare(null, null) = 0
* StringUtils.compare(null , "a") < 0
* StringUtils.compare("a", null) > 0
* StringUtils.compare("abc", "abc") = 0
* StringUtils.compare("a", "b") < 0
* StringUtils.compare("b", "a") > 0
* StringUtils.compare("a", "B") > 0
* StringUtils.compare("ab", "abc") < 0
* }</pre>
*
* @param str1 the String to compare from.
* @param str2 the String to compare to.
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal or greater than {@code str2}.
* @see #compare(String, String, boolean)
* @see String#compareTo(String)
* @since 3.5
* @deprecated Use {@link Strings#compare(String, String) Strings.CS.compare(String, String)}.
*/
@Deprecated
public static int compare(final String str1, final String str2) {
return Strings.CS.compare(str1, str2);
}
/**
* Compares two Strings lexicographically, as per {@link String#compareTo(String)}, returning :
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>
* This is a {@code null} safe version of :
* </p>
*
* <pre>
* str1.compareTo(str2)
* </pre>
*
* <p>
* {@code null} inputs are handled according to the {@code nullIsLess} parameter. Two {@code null} references are considered equal.
* </p>
*
* <pre>{@code
* StringUtils.compare(null, null, *) = 0
* StringUtils.compare(null , "a", true) < 0
* StringUtils.compare(null , "a", false) > 0
* StringUtils.compare("a", null, true) > 0
* StringUtils.compare("a", null, false) < 0
* StringUtils.compare("abc", "abc", *) = 0
* StringUtils.compare("a", "b", *) < 0
* StringUtils.compare("b", "a", *) > 0
* StringUtils.compare("a", "B", *) > 0
* StringUtils.compare("ab", "abc", *) < 0
* }</pre>
*
* @param str1 the String to compare from.
* @param str2 the String to compare to.
* @param nullIsLess whether consider {@code null} value less than non-{@code null} value.
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal ou greater than {@code str2}.
* @see String#compareTo(String)
* @since 3.5
*/
public static int compare(final String str1, final String str2, final boolean nullIsLess) {
if (str1 == str2) { // NOSONARLINT this intentionally uses == to allow for both null
return 0;
}
if (str1 == null) {
return nullIsLess ? -1 : 1;
}
if (str2 == null) {
return nullIsLess ? 1 : -1;
}
return str1.compareTo(str2);
}
/**
* Compares two Strings lexicographically, ignoring case differences, as per {@link String#compareToIgnoreCase(String)}, returning :
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>
* This is a {@code null} safe version of:
* </p>
*
* <pre>
* str1.compareToIgnoreCase(str2)
* </pre>
*
* <p>
* {@code null} value is considered less than non-{@code null} value. Two {@code null} references are considered equal. Comparison is case insensitive.
* </p>
*
* <pre>{@code
* StringUtils.compareIgnoreCase(null, null) = 0
* StringUtils.compareIgnoreCase(null , "a") < 0
* StringUtils.compareIgnoreCase("a", null) > 0
* StringUtils.compareIgnoreCase("abc", "abc") = 0
* StringUtils.compareIgnoreCase("abc", "ABC") = 0
* StringUtils.compareIgnoreCase("a", "b") < 0
* StringUtils.compareIgnoreCase("b", "a") > 0
* StringUtils.compareIgnoreCase("a", "B") < 0
* StringUtils.compareIgnoreCase("A", "b") < 0
* StringUtils.compareIgnoreCase("ab", "ABC") < 0
* }</pre>
*
* @param str1 the String to compare from.
* @param str2 the String to compare to.
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal ou greater than {@code str2}, ignoring case differences.
* @see #compareIgnoreCase(String, String, boolean)
* @see String#compareToIgnoreCase(String)
* @since 3.5
* @deprecated Use {@link Strings#compare(String, String) Strings.CI.compare(String, String)}.
*/
@Deprecated
public static int compareIgnoreCase(final String str1, final String str2) {
return Strings.CI.compare(str1, str2);
}
/**
* Compares two Strings lexicographically, ignoring case differences, as per {@link String#compareToIgnoreCase(String)}, returning :
* <ul>
* <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li>
* <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li>
* <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li>
* </ul>
*
* <p>
* This is a {@code null} safe version of :
* </p>
* <pre>
* str1.compareToIgnoreCase(str2)
* </pre>
*
* <p>
* {@code null} inputs are handled according to the {@code nullIsLess} parameter. Two {@code null} references are considered equal. Comparison is case
* insensitive.
* </p>
*
* <pre>{@code
* StringUtils.compareIgnoreCase(null, null, *) = 0
* StringUtils.compareIgnoreCase(null , "a", true) < 0
* StringUtils.compareIgnoreCase(null , "a", false) > 0
* StringUtils.compareIgnoreCase("a", null, true) > 0
* StringUtils.compareIgnoreCase("a", null, false) < 0
* StringUtils.compareIgnoreCase("abc", "abc", *) = 0
* StringUtils.compareIgnoreCase("abc", "ABC", *) = 0
* StringUtils.compareIgnoreCase("a", "b", *) < 0
* StringUtils.compareIgnoreCase("b", "a", *) > 0
* StringUtils.compareIgnoreCase("a", "B", *) < 0
* StringUtils.compareIgnoreCase("A", "b", *) < 0
* StringUtils.compareIgnoreCase("ab", "abc", *) < 0
* }</pre>
*
* @param str1 the String to compare from.
* @param str2 the String to compare to.
* @param nullIsLess whether consider {@code null} value less than non-{@code null} value.
* @return < 0, 0, > 0, if {@code str1} is respectively less, equal ou greater than {@code str2}, ignoring case differences.
* @see String#compareToIgnoreCase(String)
* @since 3.5
*/
public static int compareIgnoreCase(final String str1, final String str2, final boolean nullIsLess) {
if (str1 == str2) { // NOSONARLINT this intentionally uses == to allow for both null
return 0;
}
if (str1 == null) {
return nullIsLess ? -1 : 1;
}
if (str2 == null) {
return nullIsLess ? 1 : -1;
}
return str1.compareToIgnoreCase(str2);
}
/**
* Tests if CharSequence contains a search CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String)} if possible.
*
* <p>A {@code null} CharSequence will return {@code false}.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
* StringUtils.contains("", "") = true
* StringUtils.contains("abc", "") = true
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @return true if the CharSequence contains the search CharSequence,
* false if not or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from contains(String, String) to contains(CharSequence, CharSequence)
* @deprecated Use {@link Strings#contains(CharSequence, CharSequence) Strings.CS.contains(CharSequence, CharSequence)}.
*/
@Deprecated
public static boolean contains(final CharSequence seq, final CharSequence searchSeq) {
return Strings.CS.contains(seq, searchSeq);