如何将每个句子中的第一个单词大写 Swift

How to capitalize first word in every sentence with Swift

考虑到用户区域设置,我怎样才能将段落中每个句子的第一个单词大写?我想要实现的是无论句子中的大小写如何,每个单词的第一个字母都是大写的,其余的都是小写的。我只能做一个句子,首先将所有内容都转换为小写,然后获取第一个字母并转为大写,最后将它们加在一起。我的问题与 不同,因为我不想将每个单词都大写。我只想将每个句子的第一个单词大写。 capitalizedString

"this is first sentence. this is second sentence."

"This Is First Sentence. This Is Second Sentence."

我要的是

"This is first sentence. This is second sentence."

我的问题也不同于 Capitalise first letter of every sentence 因为@rintaro 的代码不适用于我下面的示例。它保持原始文本中的大写字母完整无缺。使用@rintaro 的代码;

之前

"someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ"

之后

"SomeSentenceWith UTF text İŞğĞ. AnotherSentenceğüÜğ."

我想达到的目标,

"Somesentencewith utf text işğğ. Anothersentenceğüüğ." 

我下面的代码只能进行部分转换。

var description = "someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ"
description = description.lowercaseStringWithLocale(NSLocale.currentLocale())
let first = description.startIndex
let rest = advance(first,1)..<description.endIndex
let capitalised = description[first...first].uppercaseStringWithLocale(NSLocale.currentLocale()) + description[rest]

如果您能仔细阅读我的问题,我将不胜感激,因为这是我第三次编辑问题。如果我不能问清楚,我真的很抱歉,因为我不是母语人士。所以即使@rintaro 回答了类似的问题,他的回答并没有解决我的问题。 @martin-r 提出了一个 Objective-C 的答案,这又不能解决我遇到的问题。还有另一个用户 eric something 也提出了另一个答案,但后来被删除了。我只是不明白为什么几个人提出了不同的答案,但没有回答我的问题。

尝试:

let str = "someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ"

var result = ""
str.uppercaseString.enumerateSubstringsInRange(indices(str), options: .BySentences) { (sub, _, _, _)  in
    result += sub[sub.startIndex ... sub.startIndex]
    result += sub[sub.startIndex.successor() ..< sub.endIndex].lowercaseString
}

println(result) // -> "Somesentencewith utf text i̇şğğ. Anothersentenceğüüğ"

添加:Swift2

let str = "someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ"

var result = ""
str.uppercaseString.enumerateSubstringsInRange(str.characters.indices, options: .BySentences) { (sub, _, _, _)  in
    result += String(sub!.characters.prefix(1))
    result += String(sub!.characters.dropFirst(1)).lowercaseString
}

print(result)

您可以使用正则表达式来实现这一点。我将此函数添加为 String 扩展,因此将来调用起来很简单:

extension String {

    func toUppercaseAtSentenceBoundary() -> String {
        var string = self.lowercaseString

        var capacity = string.utf16Count
        var mutable = NSMutableString(capacity: capacity)
        mutable.appendString(string)

        var error: NSError?

        if let regex = NSRegularExpression(
            pattern: "(?:^|\b\.[ ]*)(\p{Ll})",
            options: NSRegularExpressionOptions.AnchorsMatchLines,
            error: &error
            ) {

            if let results = regex.matchesInString(
                string,
                options: NSMatchingOptions.allZeros,
                range: NSMakeRange(0, capacity)
                ) as? [NSTextCheckingResult] {

                    for result in results {
                        let numRanges = result.numberOfRanges
                        if numRanges >= 1 {
                            for i in 1..<numRanges {
                                let range = result.rangeAtIndex(i)
                                let substring = mutable.substringWithRange(range)
                                mutable.replaceCharactersInRange(range, withString: substring.uppercaseString)
                            }
                        }
                    }
            }
        }

        return mutable
    }
}

var string = "someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ.".toUppercaseAtSentenceBoundary()

更新@rintaro 的代码 Swift 3:

let str = "someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ"

var result = ""
str.uppercased().enumerateSubstrings(in: str.startIndex..<str.endIndex, options: .bySentences) { (sub, _, _, _)  in
    result += String(sub!.characters.prefix(1))
    result += String(sub!.characters.dropFirst(1)).lowercased()
}

print(result)

我根据@Katy的代码

在Swift3中写了这个扩展
extension String {

func toUppercaseAtSentenceBoundary() -> String {

 var result = ""
    self.uppercased().enumerateSubstrings(in: self.startIndex..<self.endIndex, options: .bySentences) { (sub, _, _, _)  in
        result += String(sub!.characters.prefix(1))
        result += String(sub!.characters.dropFirst(1)).lowercased()
    }

    return result as String 
  }
}

使用方法:

let string = "This is First sentence. This is second Sentence.".toUppercaseAtSentenceBoundary() 
print(string) /* Output: "This is first sentence. This is second sentence." */