例如,如果我有字符串:
“世界上所有的苹果都像橙子和草莓一样圆,但它们看起来不像香蕉。另一方面,西瓜很像菠萝。苹果是红色的,香蕉是黄色的。”
我想找到并替换字符串中的所有水果。我有一个清单:
fruit[apples, oranges, strawberries, bananas, watermelons, pineapples]
我需要用我选择的蔬菜替换所有这些;指定了映射(例如'apples'='cabbage'),因此它是一个简单的查找和替换。假设字符串继续,一些水果重复。
除了为每个列表成员使用'While'循环并在每个列表成员上执行Replace
之外,还有更短的方法吗?
答案 0 :(得分:2)
这是我对你的问题的看法,创建两个数组,一个是要找到的果实,一个是在同一地址中替换的vegies。
随时循环播放数组。
Sub Main()
Dim X As Long, FruitArr As Variant, VegArr As Variant, MyStr As String
FruitArr = Array("apples", "oranges", "strawberries", "bananas", "watermelons", "pineapples")
VegArr = Array("cabbages", "potatoes", "brussell sprouts", "cucumbers", "lettuces", "eggplants")
MyStr = "All the apples in the world are round like oranges and strawberries, but they do not look like bananas. watermelons on the other hand are big like pineapples. apples are red and bananas are yellow."
For X = UBound(FruitArr) To LBound(FruitArr) Step -1
MyStr = Replace(MyStr, FruitArr(X), VegArr(X))
Next
Debug.Print MyStr
End Sub
编辑:以另一种方式将订单从lbound更改为ubound。这是菠萝在苹果之前进行测试和更换,否则菠萝的苹果部分转换不正确。
答案 1 :(得分:0)
试试这个
Sub Main()
Dim i As Integer
Dim str As String
Dim fruits As String
Dim fruitArr() As String
str = "All the apples in the world are round like oranges and strawberries, but they do not look like bananas." & _
"Watermelons on the other hand are big like pineapples. Apples are red and bananas are yellow."
If InStr(1, str, "apples") > 0 Then
fruits = "apples, oranges, strawberries, bananas, watermelons, pineapples"
fruitArr = Split(fruits, ",")
For i = LBound(fruitArr) To UBound(fruitArr)
If fruitArr(i) = "apples" Then
str = Replace(str, "apples", "cabbage")
End If
Next
End If
Debug.Print str
End Sub