我是编程新手。我做了一个删除阿拉伯语文本输入元音的函数。我的问题是,如果我使用最好的循环来完成任务,还是有更好更简洁的方法来编写它?
改进代码会很好。谢谢。
// It seems to work now. I solved it.
// What do you think? :) Happy that I managed to solve it.
// Programming is fun!!! :D
var arabic:String = "الْعَرَبِيَّةُ لُغَةٌ جَمِيلَةٌ"
func txtStripper(arabic: String) -> String {
var strippedTxt = ""
for character in arabic {
if character != "َ" && character != "ِ" && character != "ّ" && character != "ْ" && character != "ُ" && character != "ٌ" && character != "ً" && character != "ٍ" {
strippedTxt += toString(print(character))
}
}
return strippedTxt
}
txtStripper(arabic)
答案 0 :(得分:0)
首先,您可以使用if
函数清理contains
语句。
func txtStripper(arabic: String) -> String {
var strippedTxt = ""
let vowels : Character[] = ["َ", "ِ", "ّ", "ْ", "ُ", "ٌ", "ً", "ٍ"]
for character in arabic {
if !contains (vowels, character) {
strippedTxt += toString(character)
}
}
return strippedTxt
}
接下来,如果您对闭包感到满意,可以用更简洁的方式重写整个函数,如下所示:
func txtStripperWithClosures(arabic:String) -> String {
let vowels : Character[] = ["َ", "ِ", "ّ", "ْ", "ُ", "ٌ", "ً", "ٍ"]
return Array(arabic).filter({!contains(vowels, $0)}).reduce("",+)
}
它的工作原理如下:
Array(arabic)
将字符串转换为字符[] filter({!contains(vowels, $0)})
从数组中删除元音字符reduce("",+)
将字符列表重新加入String