@@ -13,15 +13,26 @@ extension String {
13
13
var pieces = [ String] ( )
14
14
var currentPiece = " "
15
15
16
- for (idx, character) in enumerated ( ) {
17
- if idx == 0 {
16
+ for (idx, character) in zip ( indices , self ) {
17
+ if idx == startIndex {
18
18
currentPiece += character. uppercased ( )
19
19
} else if character. isUppercase {
20
20
// Small check: recognize runs of multiple uppercase letters and
21
- // consider them part of the same word.
22
- if let previousChar = currentPiece. last, previousChar. isUppercase {
21
+ // consider them part of the same word until the start of the next word.
22
+ let previousIndex = index ( before: idx)
23
+ let nextIndex = index ( after: idx)
24
+ let previous = self [ previousIndex]
25
+ let next = nextIndex < endIndex ? self [ nextIndex] : nil
26
+ if previous. isUppercase && next? . isLowercase == true {
27
+ // Previous word was an initialism, and this uppercase letter starts a new word
28
+ // containing the next character.
29
+ pieces. append ( currentPiece)
30
+ currentPiece = String ( character)
31
+ } else if previous. isUppercase {
32
+ // Continue the initialism.
23
33
currentPiece. append ( character)
24
34
} else {
35
+ // Previous word was not an initialism, start a new word.
25
36
pieces. append ( currentPiece)
26
37
currentPiece = character. uppercased ( )
27
38
}
@@ -30,7 +41,7 @@ extension String {
30
41
}
31
42
}
32
43
33
- // Commit the last bit of the phrase
44
+ // Commit the last bit of the phrase.
34
45
if !currentPiece. isEmpty {
35
46
pieces. append ( currentPiece)
36
47
}
0 commit comments