Swift IOS, How to capitalize letters of a sentance inputed by app user, example ; 4th letter and 6th letter?

后端 未结 1 543
小鲜肉
小鲜肉 2021-01-29 16:34

The user inputs a sentence in text-field , and than enters the number 4 in a text-field and 6 in another text-field. It Capitalize the sentence at where the 4th letter is and t

1条回答
  •  一整个雨季
    2021-01-29 17:21

    Is this what you're looking for?

    func capitalize(string: String, positions: IndexSet) -> String {
        let range = (0.. 0,
            positions.allSatisfy({ range ~= $0 }) else {
            fatalError("Couldn't capitalize")
        }
    
        return String(string.enumerated().map{ (index, char) in
            return positions.contains(index) ? String(char).capitalized.first! : char
        })
    }
    
    var str = "there are 12 months in a year"
    capitalize(string: str, positions: [3, 6])  //"theRe Are 12 months in a year"
    

    If you'd like to only count letters, and to have the counting start by 1:

    func capitalize(string: String, positions: IndexSet) -> String {
    
        guard string.count > 0 else {
            fatalError("There is nothing to capitalize")
        }
    
        let zeroBasedPositions = positions.map {$0 - 1}
    
        guard zeroBasedPositions.allSatisfy({ $0 >= 0 }) else {
            fatalError("The positions should be one-based")
        }
    
        let letterIndexes = string
            .enumerated()
            .filter { (index, char) in
                CharacterSet(charactersIn: String(char))
                    .isSubset(of: CharacterSet.letters)
            }.map { $0.0 }
    
        guard let positionsMax = zeroBasedPositions.max(),
            positionsMax <= letterIndexes.count
            else {
                fatalError("There are only \(letterIndexes.count) letters")
        }
    
        let lettersToCapitalizeIndexes = zeroBasedPositions.map { letterIndexes[$0] }
    
        return String(string.enumerated().map{ (index, char) in
            if lettersToCapitalizeIndexes.contains(index) {
                return String(char).capitalized.first!
            } else {
                return char
            }
        })
    }
    
    var str = "there are 12 months in a year"
    capitalize(string: str, positions: [4, 6])  //"theRe Are 12 months in a year"
    

    0 讨论(0)
提交回复
热议问题