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

时间:2018-07-09 10:24:39

标签: ios swift string flatmap

我尝试使用以下代码:

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

答案 0 :(得分:4)

只需将$0 ==替换为return,您正在将Character与Bool进行比较就没有意义了

let vowels: [Character] = ["a","e","i","o","u", "y"]

let replaced = String(myString.map {
     return vowels.contains($0) ? "1" : "0"
 })

答案 1 :(得分:1)

将所有元音替换为带星号的字符串

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)

答案 2 :(得分:0)

您可以像这样从字符串中删除元音:

string.remove(at: string.index(where: {vowels.contains($0)})!)

答案 3 :(得分:0)

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)"
  }
}

答案 4 :(得分:-1)

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

 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

    }
}