如何替换字符串中的所有元音?
How to replace all vowels in a String?
我试过这个代码:
let vowels: [Character] = ["a","e","i","o","u", "y"]
let replaced = String(myString.map {
[=10=] == vowels.contains([=10=]) ? "1" : "0"
})
但是我有错误:
Binary operator '==' cannot be applied to operands of type 'Character' and 'Bool'
怎么了?
只需将 [=11=] ==
替换为 return
,您将 Character 与 Bool 进行比较没有任何意义
let vowels: [Character] = ["a","e","i","o","u", "y"]
let replaced = String(myString.map {
return vowels.contains([=10=]) ? "1" : "0"
})
您可以像这样从字符串中删除元音:
string.remove(at: string.index(where: {vowels.contains([=10=])})!)
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)"
}
}
用星号替换字符串中的所有元音
let vowels: [Character] = ["a","e","i","o","u", "y"]
var myString = "mahipal singh"
let replaced = String(myString.map {
vowels.contains([=10=]) ? Character("*") : [=10=] // Replace * with your character you wanna to replace
})
print(replaced)
不同的方式,但仍然如你所愿
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
}
}
我试过这个代码:
let vowels: [Character] = ["a","e","i","o","u", "y"]
let replaced = String(myString.map {
[=10=] == vowels.contains([=10=]) ? "1" : "0"
})
但是我有错误:
Binary operator '==' cannot be applied to operands of type 'Character' and 'Bool'
怎么了?
只需将 [=11=] ==
替换为 return
,您将 Character 与 Bool 进行比较没有任何意义
let vowels: [Character] = ["a","e","i","o","u", "y"]
let replaced = String(myString.map {
return vowels.contains([=10=]) ? "1" : "0"
})
您可以像这样从字符串中删除元音:
string.remove(at: string.index(where: {vowels.contains([=10=])})!)
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)"
}
}
用星号替换字符串中的所有元音
let vowels: [Character] = ["a","e","i","o","u", "y"]
var myString = "mahipal singh"
let replaced = String(myString.map {
vowels.contains([=10=]) ? Character("*") : [=10=] // Replace * with your character you wanna to replace
})
print(replaced)
不同的方式,但仍然如你所愿
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
}
}