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

标签 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 的答案,这又不能解决我遇到的问题。还有另一个用户 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)

关于swift - 如何使用 Swift 将每个句子中的第一个单词大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29283003/

相关文章:

objective-c - 组件通过字符串分隔 : @"" (every character in array)

ios - NSString concat在设备上不起作用

ios - 有没有办法快速将相机设置为横向模式?

swift - UIView Nib 中的 UICollectionView

php - 如何在 iOS 应用程序中显示重音字符实体?

objective-c - 当字符串包含时 NSScanner 失败\n

nsstring - UILabel 所需的高度取决于字符串长度(Swift、iOS 8)

ios - Swift 2 FirebaseTableView

ios - 将主队列设置为 NSOperationQueue 的底层队列

ios - 将 Playground 添​​加到 Storyboard 项目 : Could not find a storyboard . .. in bundle NSBundle