CamelCase Method

Shin Yulin
iOS 雛鳥學飛之路
Jun 18, 2021

Description:

Write a simple camelCase function for strings. All words must have their first letter capitalized and all spaces removed.

For instance:

camelCase("hello case");// ==> "HelloCase"camelCase("camel case word");// ==> "CamelCaseWord"

TryCode:

func camelCase (_ str: String) -> String{

var newStr = ""
var isAfterSapce = true
for chacter in str{
if chacter.isWhitespace{
isAfterSapce = true
continue
}else{
if isAfterSapce {
newStr.append("\\(chacter.uppercased())")
isAfterSapce = false
}else{
newStr.append("\\(chacter)")
}
}
}
return newStr
}

BetterCode:

func camelCase(_ str: String) -> String {
return str.capitalized.replacingOccurrences(of: " ", with: "")
}

Note:

.capitalized

var capitalized: [String](<https://developer.apple.com/documentation/swift/string>) { get }

自動把每段文字的首字便大寫

replacingOccurrences(of:with:)

func replacingOccurrences(of target: [String](<https://developer.apple.com/documentation/swift/string>), with replacement: [String](<https://developer.apple.com/documentation/swift/string>)) -> [String](<https://developer.apple.com/documentation/swift/string>)

替換文字

--

--