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

时间:2015-03-26 15:49:34

标签: swift nsstring

考虑到用户区域设置,如何将段落中每个句子的第一个单词大写?我想要实现的是无论句子里面的情况如何,每个单词的第一个字母都是大写的,其余的都是小写的。首先将所有内容转换为小写,然后获得第一个字母并制作大写字母,最后将它们加在一起,我只能做一个句子。我的问题与How to capitalize each word in a string using Swift iOS不同,因为我不想将每个单词都大写。我只想把每个句子的第一个单词弄清楚。 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答案,它再次解决了我的问题。有另一个用户埃里克的东西,他们也提出了另一个答案,但事后删除。我只是无法理解为什么有几个人提出了不回答我的问题的不同答案。

4 个答案:

答案 0 :(得分:7)

尝试:

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ğüüğ"

ADDED: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)

答案 1 :(得分:2)

更新@ 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)

答案 2 :(得分:1)

您可以使用正则表达式来实现此目的。我将此函数添加为字符串扩展名,因此将来调用将是微不足道的:

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()

答案 3 :(得分:1)

我根据@ Katy的代码

在Swift 3中写了这个扩展名
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." */