包含另一个String中单词的第一个字母的字符串

时间:2015-11-09 10:47:41

标签: ios swift swift2

我想要做的例子:

let string = "This is my sentence"

我希望得到这样的结果:" TIMS"

由于某种原因,我正在与swift和字符串挣扎

class func getStringOfStartingLetter(str:String) -> String{
        var firstCharacters: NSMutableString = NSMutableString()
        let words: [AnyObject] = str.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        for word in words   {
            if word.length() > 0 {
                let firstLetter: String = word.substringToIndex(1)
                firstCharacters.appendString(firstLetter.uppercaseString)
                }
        }
        return firstCharacters as String
    }

4 个答案:

答案 0 :(得分:2)

试试这个:

let str = "This is my sentence"

var strArr = str.componentsSeparatedByString(" ")
    .map() {
        $0.characters.first ?? " "
    }.reduce("") {
        initVal, obj in
        "\(initVal)\(obj)"
    }
print("Arr : \(strArr)")

你甚至可以这样做:

var a = "This is my sentence".characters.split(" ")
    .map() {
        $0.first! // Or thanks to @EricD use more safeties way: $0.first ?? " "
}

答案 1 :(得分:1)

for Objective-c我有

NSMutableString * firstCharacters = [NSMutableString string];
    NSArray * words = [@"this is my sentence" componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    for (NSString * word in words) {
      if ([word length] > 0) {
        NSString * firstLetter = [word substringToIndex:1];
        [firstCharacters appendString:[firstLetter uppercaseString]];
      }
    }

答案 2 :(得分:1)

String的好扩展名:

extension String {

    func uppercasedFirstLetters() -> String {

        let arrayOfWords = self.componentsSeparatedByString(" ")

        let firstLetters: [String] = arrayOfWords.map {

            if let character = $0.characters.first {
                return String(character)
            }
            return ""
        }

        return firstLetters.joinWithSeparator("").uppercaseString
    }
}

用法:

let outputString = "This is my string".uppercasedFirstLetters() //TIMS

答案 3 :(得分:0)

这个怎么样:

let str = "This is my sentence"

var res = str.componentsSeparatedByString(" ").reduce("") {
    if let character = $1.characters.first {
        return $0 + String(character).uppercaseString
    }
    return $0
}

print(res)