-
Notifications
You must be signed in to change notification settings - Fork 351
Expand file tree
/
Copy pathStrman.java
More file actions
1476 lines (1356 loc) · 51.9 KB
/
Strman.java
File metadata and controls
1476 lines (1356 loc) · 51.9 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
/*
*
* * The MIT License
* *
* * Copyright 2016 Shekhar Gulati <shekhargulati84@gmail.com>.
* *
* * Permission is hereby granted, free of charge, to any person obtaining a copy
* * of this software and associated documentation files (the "Software"), to deal
* * in the Software without restriction, including without limitation the rights
* * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* * copies of the Software, and to permit persons to whom the Software is
* * furnished to do so, subject to the following conditions:
* *
* * The above copyright notice and this permission notice shall be included in
* * all copies or substantial portions of the Software.
* *
* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* * THE SOFTWARE.
*
*/
package strman;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.*;
/**
* A String manipulation library without any dependencies
*/
public abstract class Strman {
private static final Predicate<String> NULL_STRING_PREDICATE = Objects::isNull;
private static final Supplier<String> NULL_STRING_MSG_SUPPLIER = () -> "'value' should be not null.";
private static final String[] EMPTY_ARRAY = new String[0];
private Strman() {
}
/**
* Appends Strings to value
*
* @param value initial String
* @param appends an array of strings to append
* @return full String
*/
public static String append(final String value, final String... appends) {
return appendArray(value, appends);
}
/**
* Append an array of String to value
*
* @param value initial String
* @param appends an array of strings to append
* @return full String
*/
public static String appendArray(final String value, final String[] appends) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (appends == null || appends.length == 0) {
return value;
}
StringJoiner joiner = new StringJoiner("");
for (String append : appends) {
joiner.add(append);
}
return value + joiner.toString();
}
/**
* Get the character at index. This method will take care of negative indexes.
* The valid value of index is between -(length-1) to (length-1).
* For values which don't fall under this range Optional.empty will be returned.
*
* @param value input value
* @param index location
* @return an Optional String if found else empty
*/
public static Optional<String> at(final String value, int index) {
if (isNullOrEmpty(value)) {
return Optional.empty();
}
int length = value.length();
if (index < 0) {
index = length + index;
}
return (index < length && index >= 0) ? Optional.of(String.valueOf(value.charAt(index))) : Optional.empty();
}
/**
* Returns an array with strings between start and end.
*
* @param value input
* @param start start
* @param end end
* @return Array containing different parts between start and end.
*/
public static String[] between(final String value, final String start, final String end) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
validate(start, NULL_STRING_PREDICATE, () -> "'start' should be not null.");
validate(end, NULL_STRING_PREDICATE, () -> "'end' should be not null.");
String[] parts = value.split(end);
return Arrays.stream(parts).map(subPart -> subPart.substring(subPart.indexOf(start) + start.length()))
.toArray(String[]::new);
}
/**
* Returns a String array consisting of the characters in the String.
*
* @param value input
* @return character array
*/
public static String[] chars(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return value.split("");
}
/**
* Replace consecutive whitespace characters with a single space.
*
* @param value input String
* @return collapsed String
*/
public static String collapseWhitespace(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return value.trim().replaceAll("\\s\\s+", " ");
}
/**
* Verifies that the needle is contained in the value. The search is case insensitive
*
* @param value to search
* @param needle to find
* @return true if found else false.
*/
public static boolean contains(final String value, final String needle) {
return contains(value, needle, false);
}
/**
* Verifies that the needle is contained in the value.
*
* @param value to search
* @param needle to find
* @param caseSensitive true or false
* @return true if found else false.
*/
public static boolean contains(final String value, final String needle, final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (caseSensitive) {
return value.contains(needle);
}
return value.toLowerCase().contains(needle.toLowerCase());
}
/**
* Verifies that all needles are contained in value. The search is case insensitive
*
* @param value input String to search
* @param needles needles to find
* @return true if all needles are found else false.
*/
public static boolean containsAll(final String value, final String[] needles) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return Arrays.stream(needles).allMatch(needle -> contains(value, needle, false));
}
/**
* Verifies that all needles are contained in value
*
* @param value input String to search
* @param needles needles to find
* @param caseSensitive true or false
* @return true if all needles are found else false.
*/
public static boolean containsAll(final String value, final String[] needles, final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return Arrays.stream(needles).allMatch(needle -> contains(value, needle, caseSensitive));
}
/**
* Verifies that one or more of needles are contained in value. This is case insensitive
*
* @param value input
* @param needles needles to search
* @return boolean true if any needle is found else false
*/
public static boolean containsAny(final String value, final String[] needles) {
return containsAny(value, needles, false);
}
/**
* Verifies that one or more of needles are contained in value.
*
* @param value input
* @param needles needles to search
* @param caseSensitive true or false
* @return boolean true if any needle is found else false
*/
public static boolean containsAny(final String value, final String[] needles, final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return Arrays.stream(needles).anyMatch(needle -> contains(value, needle, caseSensitive));
}
/**
* Count the number of times substr appears in value
*
* @param value input
* @param subStr to search
* @return count of times substring exists
*/
public static long countSubstr(final String value, final String subStr) {
return countSubstr(value, subStr, true, false);
}
/**
* Count the number of times substr appears in value
*
* @param value input
* @param subStr search string
* @param caseSensitive whether search should be case sensitive
* @param allowOverlapping boolean to take into account overlapping
* @return count of times substring exists
*/
public static long countSubstr(final String value, final String subStr, final boolean caseSensitive,
boolean allowOverlapping) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return countSubstr(caseSensitive ? value : value.toLowerCase(), caseSensitive ? subStr : subStr.toLowerCase(),
allowOverlapping, 0L);
}
/**
* Test if value ends with search. The search is case sensitive.
*
* @param value input string
* @param search string to search
* @return true or false
*/
public static boolean endsWith(final String value, final String search) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return endsWith(value, search, value.length(), true);
}
/**
* Test if value ends with search.
*
* @param value input string
* @param search string to search
* @param caseSensitive true or false
* @return true or false
*/
public static boolean endsWith(final String value, final String search, final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return endsWith(value, search, value.length(), caseSensitive);
}
/**
* Test if value ends with search.
*
* @param value input string
* @param search string to search
* @param position position till which you want to search.
* @param caseSensitive true or false
* @return true or false
*/
public static boolean endsWith(final String value, final String search, final int position,
final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
int remainingLength = position - search.length();
if (caseSensitive) {
return value.indexOf(search, remainingLength) > -1;
}
return value.toLowerCase().indexOf(search.toLowerCase(), remainingLength) > -1;
}
/**
* Ensures that the value begins with prefix. If it doesn't exist, it's prepended. It is case sensitive.
*
* @param value input
* @param prefix prefix
* @return string with prefix if it was not present.
*/
public static String ensureLeft(final String value, final String prefix) {
return ensureLeft(value, prefix, true);
}
/**
* Ensures that the value begins with prefix. If it doesn't exist, it's prepended.
*
* @param value input
* @param prefix prefix
* @param caseSensitive true or false
* @return string with prefix if it was not present.
*/
public static String ensureLeft(final String value, final String prefix, final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (caseSensitive) {
return value.startsWith(prefix) ? value : prefix + value;
}
String _value = value.toLowerCase();
String _prefix = prefix.toLowerCase();
return _value.startsWith(_prefix) ? value : prefix + value;
}
/**
* Decodes data encoded with MIME base64
*
* @param value The data to decode
* @return decoded data
*/
public static String base64Decode(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8);
}
/**
* Encodes data with MIME base64.
*
* @param value The data to encode
* @return The encoded String
*/
public static String base64Encode(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
}
/**
* Convert binary unicode (16 digits) string to string chars
*
* @param value The value to decode
* @return The decoded String
*/
public static String binDecode(final String value) {
return decode(value, 16, 2);
}
/**
* Convert string chars to binary unicode (16 digits)
*
* @param value The value to encode
* @return String in binary format
*/
public static String binEncode(final String value) {
return encode(value, 16, 2);
}
/**
* Convert decimal unicode (5 digits) string to string chars
*
* @param value The value to decode
* @return decoded String
*/
public static String decDecode(final String value) {
return decode(value, 5, 10);
}
/**
* Convert string chars to decimal unicode (5 digits)
*
* @param value The value to encode
* @return Encoded value
*/
public static String decEncode(final String value) {
return encode(value, 5, 10);
}
/**
* Ensures that the value ends with suffix. If it doesn't, it's appended. This operation is case sensitive.
*
* @param value The input String
* @param suffix The substr to be ensured to be right
* @return The string which is guarenteed to start with substr
*/
public static String ensureRight(final String value, final String suffix) {
return ensureRight(value, suffix, true);
}
/**
* Ensures that the value ends with suffix. If it doesn't, it's appended.
*
* @param value The input String
* @param suffix The substr to be ensured to be right
* @param caseSensitive Use case (in-)sensitive matching for determining if value already ends with suffix
* @return The string which is guarenteed to start with substr
*/
public static String ensureRight(final String value, final String suffix, boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return endsWith(value, suffix, caseSensitive) ? value : append(value, suffix);
}
/**
* Returns the first n chars of String
*
* @param value The input String
* @param n Number of chars to return
* @return The first n chars
*/
public static Optional<String> first(final String value, final int n) {
return Optional.ofNullable(value).filter(v -> !v.isEmpty()).map(v -> v.substring(0, n));
}
/**
* Return the first char of String
*
* @param value The input String
* @return The first char
*/
public static Optional<String> head(final String value) {
return first(value, 1);
}
/**
* Formats a string using parameters
*
* @param value The value to be formatted
* @param params Parameters to be described in the string
* @return The formatted string
*/
public static String format(final String value, String... params) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
Pattern p = Pattern.compile("\\{(\\w+)}");
Matcher m = p.matcher(value);
String result = value;
while (m.find()) {
int paramNumber = Integer.parseInt(m.group(1));
if (params == null || paramNumber >= params.length) {
throw new IllegalArgumentException("params does not have value for " + m.group());
}
result = result.replace(m.group(), params[paramNumber]);
}
return result;
}
/**
* Convert hexadecimal unicode (4 digits) string to string chars
*
* @param value The value to decode
* @return The decoded String
*/
public static String hexDecode(final String value) {
return decode(value, 4, 16);
}
/**
* Convert string chars to hexadecimal unicode (4 digits)
*
* @param value The value to encode
* @return String in hexadecimal format.
*/
public static String hexEncode(final String value) {
return encode(value, 4, 16);
}
/**
* The indexOf() method returns the index within the calling String of the first occurrence of the specified value, starting the search at fromIndex.
* Returns -1 if the value is not found.
*
* @param value The input String
* @param needle The search String
* @param offset The offset to start searching from.
* @param caseSensitive boolean to indicate whether search should be case sensitive
* @return Returns position of first occurrence of needle.
*/
public static int indexOf(final String value, final String needle, int offset, boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (caseSensitive) {
return value.indexOf(needle, offset);
}
return value.toLowerCase().indexOf(needle.toLowerCase(), offset);
}
/**
* Tests if two Strings are inequal
*
* @param first The first String
* @param second The second String
* @return true if first and second are not equal false otherwise
*/
public static boolean unequal(final String first, final String second) {
return !Objects.equals(first, second);
}
/**
* Tests if two Strings are inequal
*
* @param first The first String
* @param second The second String
* @return true if first and second are not equal false otherwise
* @deprecated use unequal instead
*/
public static boolean inequal(final String first, final String second) {
return !Objects.equals(first, second);
}
/**
* Inserts 'substr' into the 'value' at the 'index' provided.
*
* @param value The input String
* @param substr The String to insert
* @param index The index to insert substr
* @return String with substr added
*/
public static String insert(final String value, final String substr, final int index) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
validate(substr, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (index > value.length()) {
return value;
}
return append(value.substring(0, index), substr, value.substring(index));
}
/**
* Verifies if String is uppercase
*
* @param value The input String
* @return true if String is uppercase false otherwise
*/
public static boolean isUpperCase(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
for (int i = 0; i < value.length(); i++) {
if (Character.isLowerCase(value.charAt(i))) {
return false;
}
}
return true;
}
/**
* Verifies if String is lower case
*
* @param value The input String
* @return true if String is lowercase false otherwise
*/
public static boolean isLowerCase(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
for (int i = 0; i < value.length(); i++) {
if (Character.isUpperCase(value.charAt(i))) {
return false;
}
}
return true;
}
/**
* Return the last n chars of String
*
* @param value The input String
* @param n Number of chars to return
* @return n Last characters
*/
public static String last(final String value, int n) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (n > value.length()) {
return value;
}
return value.substring(value.length() - n);
}
/**
* Returns a new string of a given length such that the beginning of the string is padded.
*
* @param value The input String
* @param pad The pad
* @param length Length of the String we want
* @return Padded String
*/
public static String leftPad(final String value, final String pad, final int length) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
validate(pad, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (value.length() > length) {
return value;
}
return append(repeat(pad, length - value.length()), value);
}
/**
* Checks whether Object is String
*
* @param value The input String
* @return true if Object is a String false otherwise
*/
public static boolean isString(final Object value) {
if (Objects.isNull(value)) {
throw new IllegalArgumentException("value can't be null");
}
return value instanceof String;
}
/**
* This method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from the offset.
* Returns -1 if the value is not found. The search starts from the end and case sensitive.
*
* @param value The input String
* @param needle The search String
* @return Return position of the last occurrence of 'needle'.
*/
public static int lastIndexOf(final String value, final String needle) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return lastIndexOf(value, needle, value.length(), true);
}
/**
* This method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from the offset.
* Returns -1 if the value is not found. The search starts from the end and case sensitive.
*
* @param value The input String
* @param needle The search String
* @param caseSensitive true or false
* @return Return position of the last occurrence of 'needle'.
*/
public static int lastIndexOf(final String value, final String needle, boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return lastIndexOf(value, needle, value.length(), caseSensitive);
}
/**
* This method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from the offset.
* Returns -1 if the value is not found.
*
* @param value The input String
* @param needle The search String
* @param offset The index to start search from
* @param caseSensitive whether search should be case sensitive
* @return Return position of the last occurrence of 'needle'.
*/
public static int lastIndexOf(final String value, final String needle, final int offset,
final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
validate(needle, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (caseSensitive) {
return value.lastIndexOf(needle, offset);
}
return value.toLowerCase().lastIndexOf(needle.toLowerCase(), offset);
}
/**
* Removes all spaces on left
*
* @param value The input String
* @return String without left border spaces
*/
public static String leftTrim(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return value.replaceAll("^\\s+", "");
}
/**
* Returns length of String. Delegates to java.lang.String length method.
*
* @param value The input String
* @return Length of the String
*/
public static int length(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return value.length();
}
/**
* Return a new String starting with prepends
*
* @param value The input String
* @param prepends Strings to prepend
* @return The prepended String
*/
public static String prepend(final String value, final String... prepends) {
return prependArray(value, prepends);
}
/**
* Return a new String starting with prepends
*
* @param value The input String
* @param prepends Strings to prepend
* @return The prepended String
*/
public static String prependArray(final String value, final String[] prepends) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (prepends == null || prepends.length == 0) {
return value;
}
StringJoiner joiner = new StringJoiner("");
for (String prepend : prepends) {
joiner.add(prepend);
}
return joiner.toString() + value;
}
/**
* Remove empty Strings from string array
*
* @param strings Array of String to be cleaned
* @return Array of String without empty Strings
*/
public static String[] removeEmptyStrings(String[] strings) {
if (Objects.isNull(strings)) {
throw new IllegalArgumentException("Input array should not be null");
}
return Arrays.stream(strings).filter(str -> str != null && !str.trim().isEmpty()).toArray(String[]::new);
}
/**
* Returns a new String with the prefix removed, if present. This is case sensitive.
*
* @param value The input String
* @param prefix String to remove on left
* @return The String without prefix
*/
public static String removeLeft(final String value, final String prefix) {
return removeLeft(value, prefix, true);
}
/**
* Returns a new String with the prefix removed, if present.
*
* @param value The input String
* @param prefix String to remove on left
* @param caseSensitive ensure case sensitivity
* @return The String without prefix
*/
public static String removeLeft(final String value, final String prefix, final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
validate(prefix, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (caseSensitive) {
return value.startsWith(prefix) ? value.substring(prefix.length()) : value;
}
return value.toLowerCase().startsWith(prefix.toLowerCase()) ? value.substring(prefix.length()) : value;
}
/**
* Remove all non word characters.
*
* @param value The input String
* @return String without non-word characters
*/
public static String removeNonWords(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return value.replaceAll("[^\\w]+", "");
}
/**
* Returns a new string with the 'suffix' removed, if present. Search is case sensitive.
*
* @param value The input String
* @param suffix The suffix to remove
* @return The String without suffix!
*/
public static String removeRight(final String value, final String suffix) {
return removeRight(value, suffix, true);
}
/**
* Returns a new string with the 'suffix' removed, if present.
*
* @param value The input String
* @param suffix The suffix to remove
* @param caseSensitive whether search should be case sensitive or not
* @return The String without suffix!
*/
public static String removeRight(final String value, final String suffix, final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
validate(suffix, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return endsWith(value, suffix, caseSensitive) ? value
.substring(0, value.toLowerCase().lastIndexOf(suffix.toLowerCase())) : value;
}
/**
* Remove all spaces and replace for value.
*
* @param value The input String
* @return String without spaces
*/
public static String removeSpaces(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return value.replaceAll("\\s", "");
}
/**
* Returns a repeated string given a multiplier.
*
* @param value The input String
* @param multiplier Number of repeats
* @return The String repeated
*/
public static String repeat(final String value, final int multiplier) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return Stream.generate(() -> value).limit(multiplier).collect(joining());
}
/**
* Replace all occurrences of 'search' value to 'newvalue'. Uses String replace method.
*
* @param value The input
* @param search The String to search
* @param newValue The String to replace
* @param caseSensitive whether search should be case sensitive or not
* @return String replaced with 'newvalue'.
*/
public static String replace(final String value, final String search, final String newValue,
final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
validate(search, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (caseSensitive) {
return value.replace(search, newValue);
}
return Pattern.compile(search, Pattern.CASE_INSENSITIVE).matcher(value)
.replaceAll(Matcher.quoteReplacement(newValue));
}
/**
* Reverse the input String
*
* @param value The input String
* @return Reversed String
*/
public static String reverse(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return new StringBuilder(value).reverse().toString();
}
/**
* Returns a new string of a given length such that the ending of the string is padded.
*
* @param value The input String
* @param length Max length of String.
* @param pad Character to repeat
* @return Right padded String
*/
public static String rightPad(final String value, String pad, final int length) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
validate(pad, v -> v.length() != 1, () -> "'pad' should be only ONE charater");
if (value.length() > length) {
return value;
}
return append(value, repeat(pad, length - value.length()));
}
/**
* Remove all spaces on right.
*
* @param value The String
* @return String without right boarders spaces.
*/
public static String rightTrim(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return value.replaceAll("\\s+$", "");
}
/**
* Truncate the string securely, not cutting a word in half. It always returns the last full word.
*
* @param value The input String
* @param length Max size of the truncated String
* @param filler String that will be added to the end of the return string. Example: '...'
* @return The truncated String
*/
public static String safeTruncate(final String value, final int length, final String filler) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (length == 0) {
return "";
}
if (length >= value.length()) {
return value;
}
String[] words = words(value);
StringJoiner result = new StringJoiner(" ");
int spaceCount = 0;
for (String word : words) {
if (result.length() + word.length() + filler.length() + spaceCount > length) {
break;
} else {
result.add(word);
spaceCount++;
}
}
return append(result.toString(), filler);
}
/**
* Alias to String split function. Defined only for completeness.
*
* @param value The input String
* @param regex The delimiting regular expression
* @return String Array
*/
public static String[] split(final String value, final String regex) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return value.split(regex);
}
/**
* Splits a String to words
*
* @param value The input String
* @return Words Array
*/
public static String[] words(final String value) {
return words(value, "\\s+");
}
/**
* Splits a String to words by delimiter, \s+ by default
*
* @param value The input String
* @param delimiter delimiter for splitting input String
* @return words array
*/
public static String[] words(final String value, final String delimiter) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return value.split(delimiter);
}
/**
* Truncate the unsecured form string, cutting the independent string of required position.
*
* @param value Value will be truncated unsecurely.
* @param length Size of the returned string.
* @param filler Value that will be added to the end of the return string. Example: '...'
* @return String truncated unsafely.
*/
public static String truncate(final String value, final int length, final String filler) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (length == 0) {
return "";
}
if (length >= value.length()) {
return value;
}
return append(value.substring(0, length - filler.length()), filler);
}
/**
* Converts all HTML entities to applicable characters.
*
* @param encodedHtml The encoded HTML
* @return The decoded HTML
*/
public static String htmlDecode(final String encodedHtml) {
validate(encodedHtml, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
String[] entities = encodedHtml.split("&\\W+;");
return Arrays.stream(entities).map(e -> HtmlEntities.decodedEntities.get(e)).collect(joining());
}
/**
* Convert all applicable characters to HTML entities.
*
* @param html The HTML to encode
* @return The encoded data
*/
public static String htmlEncode(final String html) {
validate(html, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return html.chars().mapToObj(c -> "\\u" + String.format("%04x", c).toUpperCase())
.map(HtmlEntities.encodedEntities::get).collect(joining());
}
/**
* It returns a string with its characters in random order.
*
* @param value The input String
* @return The shuffled String
*/
public static String shuffle(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
String[] chars = chars(value);
Random random = new Random();
for (int i = 0; i < chars.length; i++) {
int r = random.nextInt(chars.length);
String tmp = chars[i];
chars[i] = chars[r];
chars[r] = tmp;
}
return Arrays.stream(chars).collect(joining());
}
/**
* Alias of substring method
*
* @param value The input String
* @param begin Start of slice.
* @param end End of slice.
* @return The String sliced!
*/
public static String slice(final String value, int begin, int end) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);