Swift IOS,如何大写应用程序用户输入的情感字母,例如;第4个字母和第6个字母? [英] Swift IOS, How to capitalize letters of a sentance inputed by app user, example ; 4th letter and 6th letter?

查看:88
本文介绍了Swift IOS,如何大写应用程序用户输入的情感字母,例如;第4个字母和第6个字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户在文本字段中输入一个句子, 然后在一个文本字段中输入数字4,在另一个文本字段中输入数字6.将第4个字母和第6个字母位于的句子大写.

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 the 6th letter is.

例如,用户输入:一年中有12个月"

For Example user enters: "there are 12 months in a year"

输出为:一年12个月".

The output will be: "theRe Are 12 months a year".

如何在句子中大写4-6个字母?

How to capitalize the 4th a 6th letters in a sentence?:

推荐答案

这是您要寻找的吗?

func capitalize(string: String, positions: IndexSet) -> String {
    let range = (0..<string.count)
    guard string.count > 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"


如果您只想计算字母,并且要从1开始算数,


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"

这篇关于Swift IOS,如何大写应用程序用户输入的情感字母,例如;第4个字母和第6个字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆