忽略swift中以小写字母开头的字母

时间:2016-03-02 04:56:44

标签: ios string swift

这就是我要做的事情:

let courseName = "Bachelor of Tourism Administration(B.T.A)".condensedWhitespace
let upperCaseCourseName = courseName.uppercaseString

let extrctCourseName = upperCaseCourseName.componentsSeparatedByString(" ").reduce("") { $0.0 + String($0.1.characters.first!) }

let upperCasecourseFirstCharcters = extrctCourseName

print(upperCasecourseFirstCharcters) // output : "BOTA" but i want "BTA"

因为您看到"Bachelor of Tourism Administration(B.T.A)"的outPut为BOTA但所需的输出为BTA,因为单词of从lowerCase开始,我想忽略该单词在我的这个方法中,怎么会这样做呢?

3 个答案:

答案 0 :(得分:2)

let courseName = "Bachelor of Tourism Administration(B.T.A)" //.condensedWhitespace
        var newString = ""
        let array : NSArray = courseName.componentsSeparatedByString(" ")
        for chr in array {
            let str = chr as! NSString
            if str.lowercaseString != str{
                if newString.characters.count > 0{
                    newString = newString.stringByAppendingString(" "+(str as String))
                    continue
                }
                newString = newString.stringByAppendingString((str as String))
            }
        }

        let upperCaseCourseName = newString.uppercaseString
        let extrctCourseName = upperCaseCourseName.componentsSeparatedByString(" ").reduce("") { $0.0 + String($0.1.characters.first!) }
        let upperCasecourseFirstCharcters = extrctCourseName
        print(upperCasecourseFirstCharcters)

//这将蔑视你的问题/。让我知道它是否适用于你

答案 1 :(得分:1)

干净的方法是:

extension Character
{
  public func isUpper() -> Bool
  {
    let characterString = String(self)
    return (characterString == characterString.uppercaseString) && (characterString != characterString.lowercaseString)
  }
}


let courseName = "Bachelor of Tourism Administration(B.T.A)"
let upperCaseCourseName = courseName

let extrctCourseName = upperCaseCourseName.componentsSeparatedByString(" ").reduce("") {
  if($0.1.characters.first!.isUpper()) {
    return $0.0 + String($0.1.characters.first!)
  }else {
    return $0.0
  }

}

答案 2 :(得分:1)

您可以将其粘贴到游乐场:

extension String {

    func array() -> [String] {
        return self.componentsSeparatedByString(" ")
    }

    func abbreviate() -> String {
        var output = ""
        let array = self.array()

        for word in array {
            let index = word.startIndex.advancedBy(0)
            let str = String(word[index])

            if str.lowercaseString != str {
                output += str
            }
        }
        return output
    }
}


let courseName = "Bachelor of Tourism Administration(B.T.A)".abbreviate()
print(courseName) // prints BTA