我想将CamelCase字符串分隔成一个新字符串中以空格分隔的单词。以下是我到目前为止的情况:
var camelCaps: String {
guard self.count > 0 else { return self }
var newString: String = ""
let uppercase = CharacterSet.uppercaseLetters
let first = self.unicodeScalars.first!
newString.append(Character(first))
for scalar in self.unicodeScalars.dropFirst() {
if uppercase.contains(scalar) {
newString.append(" ")
}
let character = Character(scalar)
newString.append(character)
}
return newString
}
let aCamelCaps = "aCamelCaps"
let camelCapped = aCamelCaps.camelCaps // Produce: "a Camel Caps"
let anotherCamelCaps = "ÄnotherCamelCaps"
let anotherCamelCapped = anotherCamelCaps.camelCaps // "Änother Camel Caps"
我倾向于怀疑这可能不是转换为以空格分隔的单词的最有效方式,如果我将其称为紧密循环,或1000次。在Swift中有更有效的方法吗?
[编辑1:]我需要的解决方案对于Unicode标量应该保持通用,而不是特定于Roman ASCII" A..Z"。
[编辑2:]解决方案还应跳过第一个字母,即不要在第一个字母前添加空格。
[编辑3:]更新了Swift 4语法,并添加了大写字母的缓存,从而提高了非常长的字符串和紧密循环的性能。
答案 0 :(得分:7)
这是另一种为 Swift 2.x
做同样事情的方法extension String {
func camelCaseToWords() -> String {
return unicodeScalars.reduce("") {
if NSCharacterSet.uppercaseLetterCharacterSet().characterIsMember(uint_least16_t($1.value)) {
return ($0 + " " + String($1))
}
else {
return ($0 + String($1))
}
}
}
}
Swift 3.x
extension String {
func camelCaseToWords() -> String {
return unicodeScalars.reduce("") {
if CharacterSet.uppercaseLetters.contains($1) {
return ($0 + " " + String($1))
}
else {
return $0 + String($1)
}
}
}
}
可能对某人有帮助:))
答案 1 :(得分:6)
就我在旧MacBook上测试而言,您的代码似乎对短字符串足够有效:
import Foundation
extension String {
var camelCaps: String {
var newString: String = ""
let upperCase = CharacterSet.uppercaseLetters
for scalar in self.unicodeScalars {
if upperCase.contains(scalar) {
newString.append(" ")
}
let character = Character(scalar)
newString.append(character)
}
return newString
}
var camelCaps2: String {
var newString: String = ""
let upperCase = CharacterSet.uppercaseLetters
var range = self.startIndex..<self.endIndex
while let foundRange = self.rangeOfCharacter(from: upperCase,range: range) {
newString += self.substring(with: range.lowerBound..<foundRange.lowerBound)
newString += " "
newString += self.substring(with: foundRange)
range = foundRange.upperBound..<self.endIndex
}
newString += self.substring(with: range)
return newString
}
var camelCaps3: String {
struct My {
static let regex = try! NSRegularExpression(pattern: "[A-Z]")
}
return My.regex.stringByReplacingMatches(in: self, range: NSRange(0..<self.utf16.count), withTemplate: " $0")
}
}
let aCamelCaps = "aCamelCaps"
assert(aCamelCaps.camelCaps == aCamelCaps.camelCaps2)
assert(aCamelCaps.camelCaps == aCamelCaps.camelCaps3)
let t0 = Date().timeIntervalSinceReferenceDate
for _ in 0..<1_000_000 {
let aCamelCaps = "aCamelCaps"
let camelCapped = aCamelCaps.camelCaps
}
let t1 = Date().timeIntervalSinceReferenceDate
print(t1-t0) //->4.78703999519348
for _ in 0..<1_000_000 {
let aCamelCaps = "aCamelCaps"
let camelCapped = aCamelCaps.camelCaps2
}
let t2 = Date().timeIntervalSinceReferenceDate
print(t2-t1) //->10.5831440091133
for _ in 0..<1_000_000 {
let aCamelCaps = "aCamelCaps"
let camelCapped = aCamelCaps.camelCaps3
}
let t3 = Date().timeIntervalSinceReferenceDate
print(t3-t2) //->14.2085000276566
(不要尝试在Playground中测试上面的代码。这些数字取自作为CommandLine应用程序执行的单个试验。)
答案 2 :(得分:4)
我可能会迟到但我希望与Augustine P A回答或Leo Dabus评论分享一些改进。
基本上,如果我们使用upper camel case
表示法(如“DuckDuckGo”),那么代码将无法正常工作,因为它会在字符串的开头添加一个空格。
要解决此问题,这是代码的略微修改版本,使用 Swift 3.x ,并且它兼容上下两种情况:
extension String {
func camelCaseToWords() -> String {
return unicodeScalars.reduce("") {
if CharacterSet.uppercaseLetters.contains($1) {
if $0.characters.count > 0 {
return ($0 + " " + String($1))
}
}
return $0 + String($1)
}
}
}
答案 3 :(得分:4)
我同意@aircraft,正则表达式可以在一个LOC中解决这个问题!
extension String {
func titleCase() -> String {
return (self as NSString)
.replacingOccurrences(of: "([A-Z])", with: " $1", options:
.regularExpression, range: NSRange(location: 0, length: count))
// optional
.trimmingCharacters(in: .whitespacesAndNewlines)
.capitalized // If input is in llamaCase
}
}
P.S。我对snake_case → CamelCase
here有一个要点。
答案 4 :(得分:2)
我可以在较少的代码行中(并且没有CharacterSet)执行此扩展,但是,如果要在大写字母前面插入空格,则基本上必须枚举每个String。
var differentCamelCaps: String {
var newString: String = ""
for eachCharacter in self.characters {
if (eachCharacter >= "A" && eachCharacter <= "Z") == true {
newString.append(" ")
}
newString.append(eachCharacter)
}
return newString
}
答案 5 :(得分:2)
如果您想提高效率,可以使用Regular Expressions
。
extension String {
func replace(regex: NSRegularExpression, with replacer: (_ match:String)->String) -> String {
let str = self as NSString
let ret = str.mutableCopy() as! NSMutableString
let matches = regex.matches(in: str as String, options: [], range: NSMakeRange(0, str.length))
for match in matches.reversed() {
let original = str.substring(with: match.range)
let replacement = replacer(original)
ret.replaceCharacters(in: match.range, with: replacement)
}
return ret as String
}
}
let camelCaps = "aCamelCaps" // there are 3 Capital character
let pattern = "[A-Z]"
let regular = try!NSRegularExpression(pattern: pattern)
let camelCapped:String = camelCaps.replace(regex: regular) { " \($0)" }
print("Uppercase characters replaced: \(camelCapped)")
答案 6 :(得分:2)
更好的完整解决方案......基于AmitaiB的回答
extension String {
func titlecased() -> String {
return self.replacingOccurrences(of: "([A-Z])", with: " $1", options: .regularExpression, range: self.range(of: self))
.trimmingCharacters(in: .whitespacesAndNewlines)
.capitalized
}
}
答案 7 :(得分:1)
extension String {
func titlecased() -> String {
return self
.replacingOccurrences(of: "([a-z])([A-Z](?=[A-Z])[a-z]*)", with: "$1 $2", options: .regularExpression)
.replacingOccurrences(of: "([A-Z])([A-Z][a-z])", with: "$1 $2", options: .regularExpression)
.replacingOccurrences(of: "([a-z])([A-Z][a-z])", with: "$1 $2", options: .regularExpression)
.replacingOccurrences(of: "([a-z])([A-Z][a-z])", with: "$1 $2", options: .regularExpression)
}
}
在
"ThisStringHasNoSpacesButItDoesHaveCapitals"
"IAmNotAGoat"
"LOLThatsHilarious!"
"ThisIsASMSMessage"
退出
"This String Has No Spaces But It Does Have Capitals"
"I Am Not A Goat"
"LOL Thats Hilarious!"
"This Is ASMS Message" // (Difficult tohandle single letter words when they are next to acronyms.)
答案 8 :(得分:1)
Swift 5解决方案
extension String {
func camelCaseToWords() -> String {
return unicodeScalars.reduce("") {
if CharacterSet.uppercaseLetters.contains($1) {
if $0.count > 0 {
return ($0 + " " + String($1))
}
}
return $0 + String($1)
}
}
}
答案 9 :(得分:0)
这是我使用Unicode字符类想到的:(快速5)
extension String {
var titleCased: String {
self
.replacingOccurrences(of: "(\\p{UppercaseLetter}\\p{LowercaseLetter}|\\p{UppercaseLetter}+(?=\\p{UppercaseLetter}))",
with: " $1",
options: .regularExpression,
range: range(of: self)
)
.capitalized
}
}
输出:
fillPath ➝ Fill Path ThisStringHasNoSpaces ➝ This String Has No Spaces IAmNotAGoat ➝ I Am Not A Goat LOLThatsHilarious! ➝ Lol Thats Hilarious! ThisIsASMSMessage ➝ This Is Asms Message