我正在开发一个iPhone应用程序。在标签中,我希望显示用户姓名的第一个大写字母。我该怎么做?
发布于 2012-01-27 01:11:29
如果只有一个单词字符串,则使用方法
let capitalizedString = myStr.capitalized // capitalizes every word否则,对于多个单词字符串,您必须提取第一个字符,并仅将该字符设为大写。
发布于 2013-07-15 19:16:00
(2014-07-24:当前接受的答案不正确)问题非常具体:第一个字母大写,其余的小写。使用capitalizedString会产生不同的结果:“大写字符串”而不是“大写字符串”。根据区域设置,还有另一个变体,它是capitalizedStringWithLocale,但它不适用于西班牙语,目前它使用与英语相同的规则,所以我在西班牙语中是这样做的:
NSString *abc = @"this is test";
abc = [NSString stringWithFormat:@"%@%@",[[abc substringToIndex:1] uppercaseString],[abc substringFromIndex:1] ];
NSLog(@"abc = %@",abc);发布于 2016-09-27 22:56:45
如果有人仍然对2016感兴趣,这里有一个Swift 3扩展:
extension String {
func capitalizedFirst() -> String {
let first = self[self.startIndex ..< self.index(startIndex, offsetBy: 1)]
let rest = self[self.index(startIndex, offsetBy: 1) ..< self.endIndex]
return first.uppercased() + rest.lowercased()
}
func capitalizedFirst(with: Locale?) -> String {
let first = self[self.startIndex ..< self.index(startIndex, offsetBy: 1)]
let rest = self[self.index(startIndex, offsetBy: 1) ..< self.endIndex]
return first.uppercased(with: with) + rest.lowercased(with: with)
}
}然后,您可以完全按照通常的大写()或大写()的方式使用它:
myString.capitalizedFirst()或myString.capitalizedFirst(with: Locale.current)
https://stackoverflow.com/questions/9022164
复制相似问题