【发布时间】:2015-05-30 17:42:03
【问题描述】:
考虑到用户的语言环境,如何将段落中每个句子的第一个单词大写?我想要实现的是无论句子里面的大小写,每个单词的第一个字母都是大写的,其余的都是小写的。我只能做一个句子,首先将所有内容转换为小写,然后获取第一个字母并变为大写,最后将它们加在一起。我的问题与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 也提出了另一个答案,但后来被删除了。我只是不明白为什么有几个人提出了不同的答案而没有回答我的问题。
【问题讨论】:
-
我重新打开了这个问题。我承认我忽略了 "and the rest will be lowercase" 部分(这在最初的示例中并不明显)并道歉。
-
在我看来,对 rintaro 代码的微小修改应该会得到您想要的结果:只需将
result += String(first).uppercaseString + substring替换为result += String(first).uppercaseString + substring.lowercaseString。 -
先生,我对您的行为感到非常失望。您多次给出/批准了错误的答案,将问题锁定为重复。当然,它们现在已被删除,因此我无法证明任何这些事情。无论如何,下次我该怎么办,以免下次我把铲子塞进喉咙里?