/
Strings.kt
1257 lines (1087 loc) · 52.1 KB
/
Strings.kt
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
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed 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
*
* http://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.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("StringsKt")
package kotlin.text
import kotlin.comparisons.*
import kotlin.internal.contracts.*
/**
* Returns a sub sequence of this char sequence having leading and trailing characters matching the [predicate] removed.
*/
public inline fun CharSequence.trim(predicate: (Char) -> Boolean): CharSequence {
var startIndex = 0
var endIndex = length - 1
var startFound = false
while (startIndex <= endIndex) {
val index = if (!startFound) startIndex else endIndex
val match = predicate(this[index])
if (!startFound) {
if (!match)
startFound = true
else
startIndex += 1
}
else {
if (!match)
break
else
endIndex -= 1
}
}
return subSequence(startIndex, endIndex + 1)
}
/**
* Returns a string having leading and trailing characters matching the [predicate] removed.
*/
public inline fun String.trim(predicate: (Char) -> Boolean): String
= (this as CharSequence).trim(predicate).toString()
/**
* Returns a sub sequence of this char sequence having leading characters matching the [predicate] removed.
*/
public inline fun CharSequence.trimStart(predicate: (Char) -> Boolean): CharSequence {
for (index in this.indices)
if (!predicate(this[index]))
return subSequence(index, length)
return ""
}
/**
* Returns a string having leading characters matching the [predicate] removed.
*/
public inline fun String.trimStart(predicate: (Char) -> Boolean): String
= (this as CharSequence).trimStart(predicate).toString()
/**
* Returns a sub sequence of this char sequence having trailing characters matching the [predicate] removed.
*/
public inline fun CharSequence.trimEnd(predicate: (Char) -> Boolean): CharSequence {
for (index in this.indices.reversed())
if (!predicate(this[index]))
return substring(0, index + 1)
return ""
}
/**
* Returns a string having trailing characters matching the [predicate] removed.
*/
public inline fun String.trimEnd(predicate: (Char) -> Boolean): String
= (this as CharSequence).trimEnd(predicate).toString()
/**
* Returns a sub sequence of this char sequence having leading and trailing characters from the [chars] array removed.
*/
public fun CharSequence.trim(vararg chars: Char): CharSequence = trim { it in chars }
/**
* Returns a string having leading and trailing characters from the [chars] array removed.
*/
public fun String.trim(vararg chars: Char): String = trim { it in chars }
/**
* Returns a sub sequence of this char sequence having leading characters from the [chars] array removed.
*/
public fun CharSequence.trimStart(vararg chars: Char): CharSequence = trimStart { it in chars }
/**
* Returns a string having leading characters from the [chars] array removed.
*/
public fun String.trimStart(vararg chars: Char): String = trimStart { it in chars }
/**
* Returns a sub sequence of this char sequence having trailing characters from the [chars] array removed.
*/
public fun CharSequence.trimEnd(vararg chars: Char): CharSequence = trimEnd { it in chars }
/**
* Returns a string having trailing characters from the [chars] array removed.
*/
public fun String.trimEnd(vararg chars: Char): String = trimEnd { it in chars }
/**
* Returns a sub sequence of this char sequence having leading and trailing whitespace removed.
*/
public fun CharSequence.trim(): CharSequence = trim(Char::isWhitespace)
/**
* Returns a string having leading and trailing whitespace removed.
*/
@kotlin.internal.InlineOnly
public inline fun String.trim(): String = (this as CharSequence).trim().toString()
/**
* Returns a sub sequence of this char sequence having leading whitespace removed.
*/
public fun CharSequence.trimStart(): CharSequence = trimStart(Char::isWhitespace)
/**
* Returns a string having leading whitespace removed.
*/
@kotlin.internal.InlineOnly
public inline fun String.trimStart(): String = (this as CharSequence).trimStart().toString()
/**
* Returns a sub sequence of this char sequence having trailing whitespace removed.
*/
public fun CharSequence.trimEnd(): CharSequence = trimEnd(Char::isWhitespace)
/**
* Returns a string having trailing whitespace removed.
*/
@kotlin.internal.InlineOnly
public inline fun String.trimEnd(): String = (this as CharSequence).trimEnd().toString()
/**
* Returns a char sequence with content of this char sequence padded at the beginning
* to the specified [length] with the specified character or space.
*
* @param length the desired string length.
* @param padChar the character to pad string with, if it has length less than the [length] specified. Space is used by default.
* @returns Returns a string, of length at least [length], consisting of string prepended with [padChar] as many times.
* as are necessary to reach that length.
*/
public fun CharSequence.padStart(length: Int, padChar: Char = ' '): CharSequence {
if (length < 0)
throw IllegalArgumentException("Desired length $length is less than zero.")
if (length <= this.length)
return this.subSequence(0, this.length)
val sb = StringBuilder(length)
for (i in 1..(length - this.length))
sb.append(padChar)
sb.append(this)
return sb
}
/**
* Pads the string to the specified [length] at the beginning with the specified character or space.
*
* @param length the desired string length.
* @param padChar the character to pad string with, if it has length less than the [length] specified. Space is used by default.
* @returns Returns a string, of length at least [length], consisting of string prepended with [padChar] as many times.
* as are necessary to reach that length.
*/
public fun String.padStart(length: Int, padChar: Char = ' '): String
= (this as CharSequence).padStart(length, padChar).toString()
/**
* Returns a char sequence with content of this char sequence padded at the end
* to the specified [length] with the specified character or space.
*
* @param length the desired string length.
* @param padChar the character to pad string with, if it has length less than the [length] specified. Space is used by default.
* @returns Returns a string, of length at least [length], consisting of string prepended with [padChar] as many times.
* as are necessary to reach that length.
*/
public fun CharSequence.padEnd(length: Int, padChar: Char = ' '): CharSequence {
if (length < 0)
throw IllegalArgumentException("Desired length $length is less than zero.")
if (length <= this.length)
return this.subSequence(0, this.length)
val sb = StringBuilder(length)
sb.append(this)
for (i in 1..(length - this.length))
sb.append(padChar)
return sb
}
/**
* Pads the string to the specified [length] at the end with the specified character or space.
*
* @param length the desired string length.
* @param padChar the character to pad string with, if it has length less than the [length] specified. Space is used by default.
* @returns Returns a string, of length at least [length], consisting of string prepended with [padChar] as many times.
* as are necessary to reach that length.
*/
public fun String.padEnd(length: Int, padChar: Char = ' '): String
= (this as CharSequence).padEnd(length, padChar).toString()
/**
* Returns `true` if this nullable char sequence is either `null` or empty.
*/
@kotlin.internal.InlineOnly
public inline fun CharSequence?.isNullOrEmpty(): Boolean {
contract {
returns(false) implies (this@isNullOrEmpty != null)
}
return this == null || this.length == 0
}
/**
* Returns `true` if this char sequence is empty (contains no characters).
*/
@kotlin.internal.InlineOnly
public inline fun CharSequence.isEmpty(): Boolean = length == 0
/**
* Returns `true` if this char sequence is not empty.
*/
@kotlin.internal.InlineOnly
public inline fun CharSequence.isNotEmpty(): Boolean = length > 0
// implemented differently in JVM and JS
//public fun String.isBlank(): Boolean = length() == 0 || all { it.isWhitespace() }
/**
* Returns `true` if this char sequence is not empty and contains some characters except of whitespace characters.
*/
@kotlin.internal.InlineOnly
public inline fun CharSequence.isNotBlank(): Boolean = !isBlank()
/**
* Returns `true` if this nullable char sequence is either `null` or empty or consists solely of whitespace characters.
*/
@kotlin.internal.InlineOnly
public inline fun CharSequence?.isNullOrBlank(): Boolean {
contract {
returns(false) implies (this@isNullOrBlank != null)
}
return this == null || this.isBlank()
}
/**
* Iterator for characters of the given char sequence.
*/
public operator fun CharSequence.iterator(): CharIterator = object : CharIterator() {
private var index = 0
public override fun nextChar(): Char = get(index++)
public override fun hasNext(): Boolean = index < length
}
/** Returns the string if it is not `null`, or the empty string otherwise. */
@kotlin.internal.InlineOnly
public inline fun String?.orEmpty(): String = this ?: ""
/**
* Returns the range of valid character indices for this char sequence.
*/
public val CharSequence.indices: IntRange
get() = 0..length - 1
/**
* Returns the index of the last character in the char sequence or -1 if it is empty.
*/
public val CharSequence.lastIndex: Int
get() = this.length - 1
/**
* Returns `true` if this CharSequence has Unicode surrogate pair at the specified [index].
*/
public fun CharSequence.hasSurrogatePairAt(index: Int): Boolean {
return index in 0..length - 2
&& this[index].isHighSurrogate()
&& this[index + 1].isLowSurrogate()
}
/**
* Returns a substring specified by the given [range] of indices.
*/
public fun String.substring(range: IntRange): String = substring(range.start, range.endInclusive + 1)
/**
* Returns a subsequence of this char sequence specified by the given [range] of indices.
*/
public fun CharSequence.subSequence(range: IntRange): CharSequence = subSequence(range.start, range.endInclusive + 1)
/**
* Returns a subsequence of this char sequence.
*
* This extension is chosen only for invocation with old-named parameters.
* Replace parameter names with the same as those of [CharSequence.subSequence].
*/
@kotlin.internal.InlineOnly
@Suppress("EXTENSION_SHADOWED_BY_MEMBER") // false warning
@Deprecated("Use parameters named startIndex and endIndex.", ReplaceWith("subSequence(startIndex = start, endIndex = end)"))
public inline fun String.subSequence(start: Int, end: Int): CharSequence = subSequence(start, end)
/**
* Returns a substring of chars from a range of this char sequence starting at the [startIndex] and ending right before the [endIndex].
*
* @param startIndex the start index (inclusive).
* @param endIndex the end index (exclusive). If not specified, the length of the char sequence is used.
*/
@kotlin.internal.InlineOnly
public inline fun CharSequence.substring(startIndex: Int, endIndex: Int = length): String = subSequence(startIndex, endIndex).toString()
/**
* Returns a substring of chars at indices from the specified [range] of this char sequence.
*/
public fun CharSequence.substring(range: IntRange): String = subSequence(range.start, range.endInclusive + 1).toString()
/**
* Returns a substring before the first occurrence of [delimiter].
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.substringBefore(delimiter: Char, missingDelimiterValue: String = this): String {
val index = indexOf(delimiter)
return if (index == -1) missingDelimiterValue else substring(0, index)
}
/**
* Returns a substring before the first occurrence of [delimiter].
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.substringBefore(delimiter: String, missingDelimiterValue: String = this): String {
val index = indexOf(delimiter)
return if (index == -1) missingDelimiterValue else substring(0, index)
}
/**
* Returns a substring after the first occurrence of [delimiter].
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.substringAfter(delimiter: Char, missingDelimiterValue: String = this): String {
val index = indexOf(delimiter)
return if (index == -1) missingDelimiterValue else substring(index + 1, length)
}
/**
* Returns a substring after the first occurrence of [delimiter].
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.substringAfter(delimiter: String, missingDelimiterValue: String = this): String {
val index = indexOf(delimiter)
return if (index == -1) missingDelimiterValue else substring(index + delimiter.length, length)
}
/**
* Returns a substring before the last occurrence of [delimiter].
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.substringBeforeLast(delimiter: Char, missingDelimiterValue: String = this): String {
val index = lastIndexOf(delimiter)
return if (index == -1) missingDelimiterValue else substring(0, index)
}
/**
* Returns a substring before the last occurrence of [delimiter].
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.substringBeforeLast(delimiter: String, missingDelimiterValue: String = this): String {
val index = lastIndexOf(delimiter)
return if (index == -1) missingDelimiterValue else substring(0, index)
}
/**
* Returns a substring after the last occurrence of [delimiter].
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.substringAfterLast(delimiter: Char, missingDelimiterValue: String = this): String {
val index = lastIndexOf(delimiter)
return if (index == -1) missingDelimiterValue else substring(index + 1, length)
}
/**
* Returns a substring after the last occurrence of [delimiter].
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.substringAfterLast(delimiter: String, missingDelimiterValue: String = this): String {
val index = lastIndexOf(delimiter)
return if (index == -1) missingDelimiterValue else substring(index + delimiter.length, length)
}
/**
* Returns a char sequence with content of this char sequence where its part at the given range
* is replaced with the [replacement] char sequence.
* @param startIndex the index of the first character to be replaced.
* @param endIndex the index of the first character after the replacement to keep in the string.
*/
public fun CharSequence.replaceRange(startIndex: Int, endIndex: Int, replacement: CharSequence): CharSequence {
if (endIndex < startIndex)
throw IndexOutOfBoundsException("End index ($endIndex) is less than start index ($startIndex).")
val sb = StringBuilder()
sb.append(this, 0, startIndex)
sb.append(replacement)
sb.append(this, endIndex, length)
return sb
}
/**
* Replaces the part of the string at the given range with the [replacement] char sequence.
* @param startIndex the index of the first character to be replaced.
* @param endIndex the index of the first character after the replacement to keep in the string.
*/
@kotlin.internal.InlineOnly
public inline fun String.replaceRange(startIndex: Int, endIndex: Int, replacement: CharSequence): String
= (this as CharSequence).replaceRange(startIndex, endIndex, replacement).toString()
/**
* Returns a char sequence with content of this char sequence where its part at the given [range]
* is replaced with the [replacement] char sequence.
*
* The end index of the [range] is included in the part to be replaced.
*/
public fun CharSequence.replaceRange(range: IntRange, replacement: CharSequence): CharSequence
= replaceRange(range.start, range.endInclusive + 1, replacement)
/**
* Replace the part of string at the given [range] with the [replacement] string.
*
* The end index of the [range] is included in the part to be replaced.
*/
@kotlin.internal.InlineOnly
public inline fun String.replaceRange(range: IntRange, replacement: CharSequence): String
= (this as CharSequence).replaceRange(range, replacement).toString()
/**
* Returns a char sequence with content of this char sequence where its part at the given range is removed.
*
* @param startIndex the index of the first character to be removed.
* @param endIndex the index of the first character after the removed part to keep in the string.
*
* [endIndex] is not included in the removed part.
*/
public fun CharSequence.removeRange(startIndex: Int, endIndex: Int): CharSequence {
if (endIndex < startIndex)
throw IndexOutOfBoundsException("End index ($endIndex) is less than start index ($startIndex).")
if (endIndex == startIndex)
return this.subSequence(0, length)
val sb = StringBuilder(length - (endIndex - startIndex))
sb.append(this, 0, startIndex)
sb.append(this, endIndex, length)
return sb
}
/**
* Removes the part of a string at a given range.
* @param startIndex the index of the first character to be removed.
* @param endIndex the index of the first character after the removed part to keep in the string.
*
* [endIndex] is not included in the removed part.
*/
@kotlin.internal.InlineOnly
public inline fun String.removeRange(startIndex: Int, endIndex: Int): String
= (this as CharSequence).removeRange(startIndex, endIndex).toString()
/**
* Returns a char sequence with content of this char sequence where its part at the given [range] is removed.
*
* The end index of the [range] is included in the removed part.
*/
public fun CharSequence.removeRange(range: IntRange): CharSequence = removeRange(range.start, range.endInclusive + 1)
/**
* Removes the part of a string at the given [range].
*
* The end index of the [range] is included in the removed part.
*/
@kotlin.internal.InlineOnly
public inline fun String.removeRange(range: IntRange): String
= (this as CharSequence).removeRange(range).toString()
/**
* If this char sequence starts with the given [prefix], returns a new char sequence
* with the prefix removed. Otherwise, returns a new char sequence with the same characters.
*/
public fun CharSequence.removePrefix(prefix: CharSequence): CharSequence {
if (startsWith(prefix)) {
return subSequence(prefix.length, length)
}
return subSequence(0, length)
}
/**
* If this string starts with the given [prefix], returns a copy of this string
* with the prefix removed. Otherwise, returns this string.
*/
public fun String.removePrefix(prefix: CharSequence): String {
if (startsWith(prefix)) {
return substring(prefix.length)
}
return this
}
/**
* If this char sequence ends with the given [suffix], returns a new char sequence
* with the suffix removed. Otherwise, returns a new char sequence with the same characters.
*/
public fun CharSequence.removeSuffix(suffix: CharSequence): CharSequence {
if (endsWith(suffix)) {
return subSequence(0, length - suffix.length)
}
return subSequence(0, length)
}
/**
* If this string ends with the given [suffix], returns a copy of this string
* with the suffix removed. Otherwise, returns this string.
*/
public fun String.removeSuffix(suffix: CharSequence): String {
if (endsWith(suffix)) {
return substring(0, length - suffix.length)
}
return this
}
/**
* When this char sequence starts with the given [prefix] and ends with the given [suffix],
* returns a new char sequence having both the given [prefix] and [suffix] removed.
* Otherwise returns a new char sequence with the same characters.
*/
public fun CharSequence.removeSurrounding(prefix: CharSequence, suffix: CharSequence): CharSequence {
if ((length >= prefix.length + suffix.length) && startsWith(prefix) && endsWith(suffix)) {
return subSequence(prefix.length, length - suffix.length)
}
return subSequence(0, length)
}
/**
* Removes from a string both the given [prefix] and [suffix] if and only if
* it starts with the [prefix] and ends with the [suffix].
* Otherwise returns this string unchanged.
*/
public fun String.removeSurrounding(prefix: CharSequence, suffix: CharSequence): String {
if ((length >= prefix.length + suffix.length) && startsWith(prefix) && endsWith(suffix)) {
return substring(prefix.length, length - suffix.length)
}
return this
}
/**
* When this char sequence starts with and ends with the given [delimiter],
* returns a new char sequence having this [delimiter] removed both from the start and end.
* Otherwise returns a new char sequence with the same characters.
*/
public fun CharSequence.removeSurrounding(delimiter: CharSequence): CharSequence = removeSurrounding(delimiter, delimiter)
/**
* Removes the given [delimiter] string from both the start and the end of this string
* if and only if it starts with and ends with the [delimiter].
* Otherwise returns this string unchanged.
*/
public fun String.removeSurrounding(delimiter: CharSequence): String = removeSurrounding(delimiter, delimiter)
/**
* Replace part of string before the first occurrence of given delimiter with the [replacement] string.
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.replaceBefore(delimiter: Char, replacement: String, missingDelimiterValue: String = this): String {
val index = indexOf(delimiter)
return if (index == -1) missingDelimiterValue else replaceRange(0, index, replacement)
}
/**
* Replace part of string before the first occurrence of given delimiter with the [replacement] string.
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.replaceBefore(delimiter: String, replacement: String, missingDelimiterValue: String = this): String {
val index = indexOf(delimiter)
return if (index == -1) missingDelimiterValue else replaceRange(0, index, replacement)
}
/**
* Replace part of string after the first occurrence of given delimiter with the [replacement] string.
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.replaceAfter(delimiter: Char, replacement: String, missingDelimiterValue: String = this): String {
val index = indexOf(delimiter)
return if (index == -1) missingDelimiterValue else replaceRange(index + 1, length, replacement)
}
/**
* Replace part of string after the first occurrence of given delimiter with the [replacement] string.
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.replaceAfter(delimiter: String, replacement: String, missingDelimiterValue: String = this): String {
val index = indexOf(delimiter)
return if (index == -1) missingDelimiterValue else replaceRange(index + delimiter.length, length, replacement)
}
/**
* Replace part of string after the last occurrence of given delimiter with the [replacement] string.
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.replaceAfterLast(delimiter: String, replacement: String, missingDelimiterValue: String = this): String {
val index = lastIndexOf(delimiter)
return if (index == -1) missingDelimiterValue else replaceRange(index + delimiter.length, length, replacement)
}
/**
* Replace part of string after the last occurrence of given delimiter with the [replacement] string.
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.replaceAfterLast(delimiter: Char, replacement: String, missingDelimiterValue: String = this): String {
val index = lastIndexOf(delimiter)
return if (index == -1) missingDelimiterValue else replaceRange(index + 1, length, replacement)
}
/**
* Replace part of string before the last occurrence of given delimiter with the [replacement] string.
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.replaceBeforeLast(delimiter: Char, replacement: String, missingDelimiterValue: String = this): String {
val index = lastIndexOf(delimiter)
return if (index == -1) missingDelimiterValue else replaceRange(0, index, replacement)
}
/**
* Replace part of string before the last occurrence of given delimiter with the [replacement] string.
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.replaceBeforeLast(delimiter: String, replacement: String, missingDelimiterValue: String = this): String {
val index = lastIndexOf(delimiter)
return if (index == -1) missingDelimiterValue else replaceRange(0, index, replacement)
}
// public fun String.replace(oldChar: Char, newChar: Char, ignoreCase: Boolean): String // JVM- and JS-specific
// public fun String.replace(oldValue: String, newValue: String, ignoreCase: Boolean): String // JVM- and JS-specific
/**
* Returns a new string obtained by replacing each substring of this char sequence that matches the given regular expression
* with the given [replacement].
*
* The [replacement] can consist of any combination of literal text and $-substitutions. To treat the replacement string
* literally escape it with the [kotlin.text.Regex.Companion.escapeReplacement] method.
*/
@kotlin.internal.InlineOnly
public inline fun CharSequence.replace(regex: Regex, replacement: String): String = regex.replace(this, replacement)
/**
* Returns a new string obtained by replacing each substring of this char sequence that matches the given regular expression
* with the result of the given function [transform] that takes [MatchResult] and returns a string to be used as a
* replacement for that match.
*/
@kotlin.internal.InlineOnly
public inline fun CharSequence.replace(regex: Regex, noinline transform: (MatchResult) -> CharSequence): String = regex.replace(this, transform)
/**
* Replaces the first occurrence of the given regular expression [regex] in this char sequence with specified [replacement] expression.
*
* @param replacement A replacement expression that can include substitutions. See [Regex.replaceFirst] for details.
*/
@kotlin.internal.InlineOnly
public inline fun CharSequence.replaceFirst(regex: Regex, replacement: String): String = regex.replaceFirst(this, replacement)
/**
* Returns `true` if this char sequence matches the given regular expression.
*/
@kotlin.internal.InlineOnly
public inline infix fun CharSequence.matches(regex: Regex): Boolean = regex.matches(this)
/**
* Implementation of [regionMatches] for CharSequences.
* Invoked when it's already known that arguments are not Strings, so that no additional type checks are performed.
*/
internal fun CharSequence.regionMatchesImpl(thisOffset: Int, other: CharSequence, otherOffset: Int, length: Int, ignoreCase: Boolean): Boolean {
if ((otherOffset < 0) || (thisOffset < 0) || (thisOffset > this.length - length)
|| (otherOffset > other.length - length)) {
return false
}
for (index in 0 until length) {
if (!this[thisOffset + index].equals(other[otherOffset + index], ignoreCase))
return false
}
return true
}
/**
* Returns `true` if this char sequence starts with the specified character.
*/
public fun CharSequence.startsWith(char: Char, ignoreCase: Boolean = false): Boolean =
this.length > 0 && this[0].equals(char, ignoreCase)
/**
* Returns `true` if this char sequence ends with the specified character.
*/
public fun CharSequence.endsWith(char: Char, ignoreCase: Boolean = false): Boolean =
this.length > 0 && this[lastIndex].equals(char, ignoreCase)
/**
* Returns `true` if this char sequence starts with the specified prefix.
*/
public fun CharSequence.startsWith(prefix: CharSequence, ignoreCase: Boolean = false): Boolean {
if (!ignoreCase && this is String && prefix is String)
return this.startsWith(prefix)
else
return regionMatchesImpl(0, prefix, 0, prefix.length, ignoreCase)
}
/**
* Returns `true` if a substring of this char sequence starting at the specified offset [startIndex] starts with the specified prefix.
*/
public fun CharSequence.startsWith(prefix: CharSequence, startIndex: Int, ignoreCase: Boolean = false): Boolean {
if (!ignoreCase && this is String && prefix is String)
return this.startsWith(prefix, startIndex)
else
return regionMatchesImpl(startIndex, prefix, 0, prefix.length, ignoreCase)
}
/**
* Returns `true` if this char sequence ends with the specified suffix.
*/
public fun CharSequence.endsWith(suffix: CharSequence, ignoreCase: Boolean = false): Boolean {
if (!ignoreCase && this is String && suffix is String)
return this.endsWith(suffix)
else
return regionMatchesImpl(length - suffix.length, suffix, 0, suffix.length, ignoreCase)
}
// common prefix and suffix
/**
* Returns the longest string `prefix` such that this char sequence and [other] char sequence both start with this prefix,
* taking care not to split surrogate pairs.
* If this and [other] have no common prefix, returns the empty string.
* @param ignoreCase `true` to ignore character case when matching a character. By default `false`.
*/
public fun CharSequence.commonPrefixWith(other: CharSequence, ignoreCase: Boolean = false): String {
val shortestLength = minOf(this.length, other.length)
var i = 0
while (i < shortestLength && this[i].equals(other[i], ignoreCase = ignoreCase)) {
i++
}
if (this.hasSurrogatePairAt(i - 1) || other.hasSurrogatePairAt(i - 1)) {
i--
}
return subSequence(0, i).toString()
}
/**
* Returns the longest string `suffix` such that this char sequence and [other] char sequence both end with this suffix,
* taking care not to split surrogate pairs.
* If this and [other] have no common suffix, returns the empty string.
* @param ignoreCase `true` to ignore character case when matching a character. By default `false`.
*/
public fun CharSequence.commonSuffixWith(other: CharSequence, ignoreCase: Boolean = false): String {
val thisLength = this.length
val otherLength = other.length
val shortestLength = minOf(thisLength, otherLength)
var i = 0
while (i < shortestLength && this[thisLength - i - 1].equals(other[otherLength - i - 1], ignoreCase = ignoreCase)) {
i++
}
if (this.hasSurrogatePairAt(thisLength - i - 1) || other.hasSurrogatePairAt(otherLength - i - 1)) {
i--
}
return subSequence(thisLength - i, thisLength).toString()
}
// indexOfAny()
/**
* Finds the index of the first occurrence of any of the specified [chars] in this char sequence,
* starting from the specified [startIndex] and optionally ignoring the case.
*
* @param ignoreCase `true` to ignore character case when matching a character. By default `false`.
* @returns An index of the first occurrence of matched character from [chars] or -1 if none of [chars] are found.
*
*/
public fun CharSequence.indexOfAny(chars: CharArray, startIndex: Int = 0, ignoreCase: Boolean = false): Int {
if (!ignoreCase && chars.size == 1 && this is String) {
val char = chars.single()
return nativeIndexOf(char, startIndex)
}
for (index in startIndex.coerceAtLeast(0)..lastIndex) {
val charAtIndex = get(index)
if (chars.any { it.equals(charAtIndex, ignoreCase) })
return index
}
return -1
}
/**
* Finds the index of the last occurrence of any of the specified [chars] in this char sequence,
* starting from the specified [startIndex] and optionally ignoring the case.
*
* @param startIndex The index of character to start searching at. The search proceeds backward toward the beginning of the string.
* @param ignoreCase `true` to ignore character case when matching a character. By default `false`.
* @returns An index of the last occurrence of matched character from [chars] or -1 if none of [chars] are found.
*
*/
public fun CharSequence.lastIndexOfAny(chars: CharArray, startIndex: Int = lastIndex, ignoreCase: Boolean = false): Int {
if (!ignoreCase && chars.size == 1 && this is String) {
val char = chars.single()
return nativeLastIndexOf(char, startIndex)
}
for (index in startIndex.coerceAtMost(lastIndex) downTo 0) {
val charAtIndex = get(index)
if (chars.any { it.equals(charAtIndex, ignoreCase) })
return index
}
return -1
}
private fun CharSequence.indexOf(other: CharSequence, startIndex: Int, endIndex: Int, ignoreCase: Boolean, last: Boolean = false): Int {
val indices = if (!last)
startIndex.coerceAtLeast(0)..endIndex.coerceAtMost(length)
else
startIndex.coerceAtMost(lastIndex) downTo endIndex.coerceAtLeast(0)
if (this is String && other is String) { // smart cast
for (index in indices) {
if (other.regionMatches(0, this, index, other.length, ignoreCase))
return index
}
} else {
for (index in indices) {
if (other.regionMatchesImpl(0, this, index, other.length, ignoreCase))
return index
}
}
return -1
}
private fun CharSequence.findAnyOf(strings: Collection<String>, startIndex: Int, ignoreCase: Boolean, last: Boolean): Pair<Int, String>? {
if (!ignoreCase && strings.size == 1) {
val string = strings.single()
val index = if (!last) indexOf(string, startIndex) else lastIndexOf(string, startIndex)
return if (index < 0) null else index to string
}
val indices = if (!last) startIndex.coerceAtLeast(0)..length else startIndex.coerceAtMost(lastIndex) downTo 0
if (this is String) {
for (index in indices) {
val matchingString = strings.firstOrNull { it.regionMatches(0, this, index, it.length, ignoreCase) }
if (matchingString != null)
return index to matchingString
}
} else {
for (index in indices) {
val matchingString = strings.firstOrNull { it.regionMatchesImpl(0, this, index, it.length, ignoreCase) }
if (matchingString != null)
return index to matchingString
}
}
return null
}
/**
* Finds the first occurrence of any of the specified [strings] in this char sequence,
* starting from the specified [startIndex] and optionally ignoring the case.
*
* @param ignoreCase `true` to ignore character case when matching a string. By default `false`.
* @returns A pair of an index of the first occurrence of matched string from [strings] and the string matched
* or `null` if none of [strings] are found.
*
* To avoid ambiguous results when strings in [strings] have characters in common, this method proceeds from
* the beginning to the end of this string, and finds at each position the first element in [strings]
* that matches this string at that position.
*/
public fun CharSequence.findAnyOf(strings: Collection<String>, startIndex: Int = 0, ignoreCase: Boolean = false): Pair<Int, String>? =
findAnyOf(strings, startIndex, ignoreCase, last = false)
/**
* Finds the last occurrence of any of the specified [strings] in this char sequence,
* starting from the specified [startIndex] and optionally ignoring the case.
*
* @param startIndex The index of character to start searching at. The search proceeds backward toward the beginning of the string.
* @param ignoreCase `true` to ignore character case when matching a string. By default `false`.
* @returns A pair of an index of the last occurrence of matched string from [strings] and the string matched or `null` if none of [strings] are found.
*
* To avoid ambiguous results when strings in [strings] have characters in common, this method proceeds from
* the end toward the beginning of this string, and finds at each position the first element in [strings]
* that matches this string at that position.
*/
public fun CharSequence.findLastAnyOf(strings: Collection<String>, startIndex: Int = lastIndex, ignoreCase: Boolean = false): Pair<Int, String>? =
findAnyOf(strings, startIndex, ignoreCase, last = true)
/**
* Finds the index of the first occurrence of any of the specified [strings] in this char sequence,
* starting from the specified [startIndex] and optionally ignoring the case.
*
* @param ignoreCase `true` to ignore character case when matching a string. By default `false`.
* @returns An index of the first occurrence of matched string from [strings] or -1 if none of [strings] are found.
*
* To avoid ambiguous results when strings in [strings] have characters in common, this method proceeds from
* the beginning to the end of this string, and finds at each position the first element in [strings]
* that matches this string at that position.
*/
public fun CharSequence.indexOfAny(strings: Collection<String>, startIndex: Int = 0, ignoreCase: Boolean = false): Int =
findAnyOf(strings, startIndex, ignoreCase, last = false)?.first ?: -1
/**
* Finds the index of the last occurrence of any of the specified [strings] in this char sequence,
* starting from the specified [startIndex] and optionally ignoring the case.
*
* @param startIndex The index of character to start searching at. The search proceeds backward toward the beginning of the string.
* @param ignoreCase `true` to ignore character case when matching a string. By default `false`.
* @returns An index of the last occurrence of matched string from [strings] or -1 if none of [strings] are found.
*
* To avoid ambiguous results when strings in [strings] have characters in common, this method proceeds from
* the end toward the beginning of this string, and finds at each position the first element in [strings]
* that matches this string at that position.
*/
public fun CharSequence.lastIndexOfAny(strings: Collection<String>, startIndex: Int = lastIndex, ignoreCase: Boolean = false): Int =
findAnyOf(strings, startIndex, ignoreCase, last = true)?.first ?: -1
// indexOf
/**
* Returns the index within this string of the first occurrence of the specified character, starting from the specified [startIndex].
*
* @param ignoreCase `true` to ignore character case when matching a character. By default `false`.
* @returns An index of the first occurrence of [char] or -1 if none is found.
*/
public fun CharSequence.indexOf(char: Char, startIndex: Int = 0, ignoreCase: Boolean = false): Int {
return if (ignoreCase || this !is String)
indexOfAny(charArrayOf(char), startIndex, ignoreCase)
else
nativeIndexOf(char, startIndex)
}
/**
* Returns the index within this char sequence of the first occurrence of the specified [string],
* starting from the specified [startIndex].
*
* @param ignoreCase `true` to ignore character case when matching a string. By default `false`.
* @returns An index of the first occurrence of [string] or `-1` if none is found.
*/
public fun CharSequence.indexOf(string: String, startIndex: Int = 0, ignoreCase: Boolean = false): Int {
return if (ignoreCase || this !is String)
indexOf(string, startIndex, length, ignoreCase)
else
nativeIndexOf(string, startIndex)
}
/**
* Returns the index within this char sequence of the last occurrence of the specified character,
* starting from the specified [startIndex].
*
* @param startIndex The index of character to start searching at. The search proceeds backward toward the beginning of the string.
* @param ignoreCase `true` to ignore character case when matching a character. By default `false`.
* @returns An index of the first occurrence of [char] or -1 if none is found.
*/
public fun CharSequence.lastIndexOf(char: Char, startIndex: Int = lastIndex, ignoreCase: Boolean = false): Int {
return if (ignoreCase || this !is String)
lastIndexOfAny(charArrayOf(char), startIndex, ignoreCase)
else
nativeLastIndexOf(char, startIndex)
}