通过考虑用户区域设置,如何将段落中每个句子的第一个单词大写?我想要实现的是无论句子里面的情况如何,每个单词的第一个字母都是大写的,其余的都是小写的.首先将所有内容转换为
"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答案,它再次解决了我的问题.有另一个用户埃里克的东西,他们也提出了另一个答案,但事后删除.我只是无法理解为什么有几个人提出了不回答我的问题的不同答案.
您可以使用正则表达式来实现此目的.我将此函数添加为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()