练习1
- 实现一个函数,接收一个字符串,计算每个字符出现的次数。
- 按照字符出现的次数排序。
- 输出直方图。
func printCharacterCount(for string: String) {
guard string.count > 0 else { return }
var counts: [Character: Int] = [:]
for i in string {
counts[i, default: 0] += 1
}
let sortedKeys = counts.keys.sorted { counts[$0]! > counts[$1]! }
let max = counts[sortedKeys.first!]!
for key in sortedKeys {
let value = counts[key]!
let widthOfHashes = (value * 20) / max
let hashes = String(repeating: "#", count: widthOfHashes)
print("\(key) : \(hashes) \(value)")
}
}
printCharacterCount(for: "The quick brown fox jumps over the lazy dog")
技术点分析:
- guard语法糖,排除错误的情况。
- counts[i, default: 0] += 1,default关键字实现默认值。
- "!"强制解包。
- String(repeating: "#", count: widthOfHashes)初始化字符串。
输出:
: #################### 8
o : ########## 4
e : ####### 3
u : ##### 2
h : ##### 2
r : ##### 2
w : ## 1
b : ## 1
c : ## 1
q : ## 1
y : ## 1
v : ## 1
j : ## 1
p : ## 1
x : ## 1
f : ## 1
k : ## 1
t : ## 1
z : ## 1
d : ## 1
a : ## 1
i : ## 1
T : ## 1
m : ## 1
s : ## 1
n : ## 1
l : ## 1
g : ## 1
练习2
- 计算字符串中的单词数量
func numberOfWords(in sentence: String) -> Int {
var count = 0
var inWord = false
for character in sentence {
if character == " " {
if inWord {
count += 1
}
inWord = false
} else {
inWord = true
}
}
// We need to add 1 to count the final word if there was at least 1 character
if inWord {
count += 1
}
return count
}
let wordCount = numberOfWords(in: " The quick brown fox jumps over the lazy dog")
print(wordCount)
练习3
- 格式化字符串
- 输入:"Galloway, Matt",输出:"Matt Galloway"。
func sanitized(name: String) -> String? {
guard let indexOfComma = name.index(of: ",") else {
return nil
}
let indexAfterCommaSpace = name.index(indexOfComma, offsetBy: 2)
let lastNameSubstring = name[..<indexOfComma]
let firstNameSubstring = name[indexAfterCommaSpace...]
return firstNameSubstring + " " + lastNameSubstring
}
if let sanitizedName = sanitized(name: "Galloway, Matt") {
print(sanitizedName)
}
技术点:
- 字符串索引
- 子串,范围区间的使用
练习4
- 实现components(separatedBy:) 函数。
func splitting(_ string: String, delimiter: Character) -> [String] {
var returnArray: [String] = []
var lastWordIndex = string.startIndex
for i in string.indices {
if string[i] == delimiter {
let substring = string[lastWordIndex..<i]
returnArray.append(String(substring))
lastWordIndex = string.index(after: i)
}
}
// Add the final word
let substring = string[lastWordIndex..<string.endIndex]
returnArray.append(String(substring))
return returnArray
}
let pieces = splitting("Dog,Cat,Badger,Snake,Lion", delimiter: ",")
print(pieces)
技术点:
- 数组的使用
- indices的使用
练习5
- For example, if the string is "My dog is called Rover" then the resulting string would be "yM god si dellac revoR".
func reversedByWord(sentence: String) -> String {
var reversedWords = ""
var lastWordIndex = sentence.startIndex
for i in sentence.indices {
if sentence[i] == " " {
let substring = sentence[lastWordIndex..<i]
reversedWords += substring.reversed() + " "
lastWordIndex = sentence.index(after: i)
}
}
// Add the final word
let substring = sentence[lastWordIndex..<sentence.endIndex]
reversedWords += substring.reversed()
return reversedWords
}
let reversed = reversedByWord(sentence: "The quick brown fox jumps over the lazy dog")
print(reversed)
技术点:
- 使用indices遍历字符串索引。
- reversed实现字符串反转。
- substring实现内存优化(和练习4相比)
网友评论