Instead 函式

Instead 是數學上的語法,用來表示「同時替換」。比如說Instead.. a = x , b = y ,是同時把a 換成x 且把b 換成y。

]2a + b = c

]Instead.. a = x , b = y

]2x + y = c

 

強調同時的原因是,Instead.. a = b , b = a ,代表的是同時把a 換成b,且b 換成a。

]2a + b = c

]Instead.. a = b , b = a

]2b + a = c

 

在Visual Basic 裡,想用Replace 來完成這項任務,不可能。以下程式碼試圖用Replace 實現Instead,結果當然是慘兮兮。

]Dim test As String = "2a + b = c"

]test = Replace(test, "a", "b") //所有"a" 換成"b",test 得到"2b + b = c"。

]test = Replace(test, "b", "a") //test 已經變成"2b + b = c",所有"b" 換成"a",結果test 得到"2a + a = c"。

 

果然慘兮兮對吧? 最好使用字元陣列一個一個檢視。這個思考方式很入門,但是很正確。目前本人還想不到別的方法取代。

]Function Instead(ByVal Origin As String, ByVal Find As String(), ByVal Alter As String()) As String

]If ((Origin Is Nothing) Or (Find Is Nothing) Or (Alter Is Nothing)) Then

]Return Nothing

]End If

]Dim CharArray As Char() = Origin.ToCharArray

]Instead = Nothing

]For i1Char As Integer = LBound(CharArray) To UBound(CharArray) Step 1

]For i1Find As Integer = LBound(Find) To UBound(Find) Step 1

]If (i1Char + Len(Find(i1Find)) > UBound(CharArray)) Then

]Continue For

]End If

]If (Mid(Origin, i1Char + 1, Len(Find(i1Find))) = Find(i1Find)) Then

]Instead &= Alter(i1Find)

]i1Char += Len(Find(i1Find)) - 1

]IsFind = True

]Exit For

]End If

]Next

]If Not (IsFind) Then

]Instead &= CharArray(i1Char)

]End If

]Next

]Return Instead

]End Function

文章標籤
全站熱搜
創作者介紹
創作者 GPhettoH 的頭像
GPhettoH

歇息,等待明日的天空

GPhettoH 發表在 痞客邦 留言(0) 人氣(3)