查找一个string是否包含string列表的成员

例如,如果我有string:

“世界上所有的苹果都像橙子和草莓一样圆润,但它们看起来不像香蕉,另一方面西瓜又像菠萝,苹果是红色的,香蕉是黄色的。

我想find并replacestring中的所有水果。 我有一个列表:
fruit[apples, oranges, strawberries, bananas, watermelons, pineapples]
我需要用所选的蔬菜代替所有的蔬菜, 映射是指定的(例如'苹果'='cabbage'),所以这是一个简单的查找和replace。 说,string继续,一些水果重复自己。

有没有比每个列表成员使用“循环”循环,做一个更短的方法来做到这一点?

这里是我的问题,创build两个数组,一个是find的成果,一个是在相同的地址replacevegies。

循环arraysreplace,你去。

 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 

编辑:改变订单从另一个方向从一个回合到另一个回合。 这就是菠萝在苹果前被换掉了,否则菠萝的苹果部分被错误地转换了。

尝试这个

  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