代码之家  ›  专栏  ›  技术社区  ›  cmii

如何替换字符串中的所有元音?

  •  2
  • cmii  · 技术社区  · 6 年前

    我试过使用此代码:

    let vowels: [Character] = ["a","e","i","o","u", "y"]
    
    let replaced = String(myString.map {
         $0 == vowels.contains($0) ? "1" : "0"
     })
    

    但我有个错误: Binary operator '==' cannot be applied to operands of type 'Character' and 'Bool'

    怎么了?

    5 回复  |  直到 6 年前
        1
  •  4
  •   Tj3n    6 年前

    只是需要更换 $0 == 具有 return 你在把人物和布尔作比较,这是毫无意义的。

    let vowels: [Character] = ["a","e","i","o","u", "y"]
    
    let replaced = String(myString.map {
         return vowels.contains($0) ? "1" : "0"
     })
    
        2
  •  1
  •   MAhipal Singh maxkoriakin    6 年前

    用星号符号替换字符串中的所有元音

    let vowels: [Character] = ["a","e","i","o","u", "y"]
        var myString = "mahipal singh"
        let replaced = String(myString.map {
            vowels.contains($0) ? Character("*") : $0 // Replace * with your character you wanna to replace
        })
        print(replaced)
    
        3
  •  0
  •   Akshansh Thakur    6 年前

    您可以从字符串中删除元音,如下所示:

    string.remove(at: string.index(where: {vowels.contains($0)})!)
    
        4
  •  0
  •   Pranav Gupta    6 年前
    let vowels: [Character] = ["a","e","i","o","u","y","A","E","I","O","U", "Y"]
    var replaced = String()
    for char in myString {
      if !vowels.contains(char){
        replaced = "\(replaced)\(char)"
      }
    }
    
        5
  •  -1
  •   Abd    6 年前

    不同的方式,但它仍然是你想要的

     let strs = "hello world"
        var str = String()
        let vowles = ["e","o"]
        //if you want the index also use  this (index,char) in strs.enumerated()
        //if the index is not important use this char in strs
    
        for (index,char) in strs.enumerated()
    {
    
    
       var who = String(char)
        if vowles.contains(who){
            print(who)
            //replace or deleted by changing the value of who
             who = ""
            str = str + who
            print(str)
    
        }else{
            str = str + who
    
        }
    }