gpt4 book ai didi

swift - 阿拉伯文本剥离器/解析器

转载 作者:行者123 更新时间:2023-11-28 09:21:21 27 4
gpt4 key购买 nike

我是编程新手。我做了一个函数,可以删除阿拉伯语文本输入中的元音。我的问题是我是否使用了该任务的最佳循环,或者是否有更好、更简洁的方式来编写它?

如果能改进代码就好了。谢谢。

// 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)

最佳答案

首先,您可以使用 contains 函数清理 if 语句。

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) 将 String 转换为 Character[]
  • filter({!contains(vowels, $0)}) 从数组中移除元音字符
  • reduce("",+) 将字符列表连接回一个字符串

关于swift - 阿拉伯文本剥离器/解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24109443/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com