阿拉伯语文本脱衣舞娘/解析器

时间:2014-06-08 18:28:48

标签: swift

我是编程新手。我做了一个删除阿拉伯语文本输入元音的函数。我的问题是,如果我使用最好的循环来完成任务,还是有更好更简洁的方法来编写它?

改进代码会很好。谢谢。

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

1 个答案:

答案 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