我正在尝试制作一个自动更正系统,当用户输入一个大写字母的单词时,自动更正不起作用。为了解决这个问题,我复制了键入的字符串,应用了. lowercasestring,然后比较它们。如果字符串确实输入错误,则应该更正单词。然而,取而代之的单词都是小写的。所以我需要对第一个字母应用. uppercasestring。我本来觉得我可以用
nameOfString[0]
但这显然行不通。我怎么能得到字符串的第一个字母大写,然后能够打印完整的字符串与第一个字母大写?
谢谢你的帮助!
我正在尝试制作一个自动更正系统,当用户输入一个大写字母的单词时,自动更正不起作用。为了解决这个问题,我复制了键入的字符串,应用了. lowercasestring,然后比较它们。如果字符串确实输入错误,则应该更正单词。然而,取而代之的单词都是小写的。所以我需要对第一个字母应用. uppercasestring。我本来觉得我可以用
nameOfString[0]
但这显然行不通。我怎么能得到字符串的第一个字母大写,然后能够打印完整的字符串与第一个字母大写?
谢谢你的帮助!
当前回答
斯威夫特4.0
string.capitalized(with: nil)
or
string.capitalized
但是,每个单词的首字母都要大写
苹果公司的文档:
A capitalized string is a string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values. A “word” is any sequence of characters delimited by spaces, tabs, or line terminators. Some common word delimiting punctuation isn’t considered, so this property may not generally produce the desired results for multiword strings. See the getLineStart(_:end:contentsEnd:for:) method for additional information.
其他回答
我假设您想要将整个单词串的第一个单词大写。例如:“我的猫很胖,我的脂肪很松弛”应该返回“我的猫很胖,我的脂肪很松弛”。
Swift 5:
为此,您可以导入Foundation,然后使用大写的属性。例子:
import Foundation
var x = "my cat is fat, and my fat is flabby"
print(x.capitalized) //prints "My Cat Is Fat, And My Fat Is Flabby"
如果你想成为一个纯粹主义者,不导入基础,那么你可以创建一个字符串扩展。
extension String {
func capitalize() -> String {
let arr = self.split(separator: " ").map{String($0)}
var result = [String]()
for element in arr {
result.append(String(element.uppercased().first ?? " ") + element.suffix(element.count-1))
}
return result.joined(separator: " ")
}
}
然后你可以这样使用:
var x = "my cat is fat, and my fat is flabby"
print(x.capitalize()) //prints "My Cat Is Fat, And My Fat Is Flabby"
Swift 3 (xcode 8.3.3)
大写字符串的所有首字符
let str = "your string"
let capStr = str.capitalized
//Your String
全部大写
let str = "your string"
let upStr = str.uppercased()
//YOUR STRING
字符串的第一个字符只能大写
var str = "your string"
let capStr = String(str.characters.prefix(1)).uppercased() + String(str.characters.dropFirst())
//Your string
Swift 3更新
replaceRange函数现在是replaceSubrange
nameOfString.replaceSubrange(nameOfString.startIndex...nameOfString.startIndex, with: String(nameOfString[nameOfString.startIndex]).capitalized)
在viewDidLoad()方法中添加这一行。
txtFieldName.autocapitalizationType = UITextAutocapitalizationType.words
斯威夫特4.0
string.capitalized(with: nil)
or
string.capitalized
但是,每个单词的首字母都要大写
苹果公司的文档:
A capitalized string is a string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values. A “word” is any sequence of characters delimited by spaces, tabs, or line terminators. Some common word delimiting punctuation isn’t considered, so this property may not generally produce the desired results for multiword strings. See the getLineStart(_:end:contentsEnd:for:) method for additional information.