你可以寫一個,作爲一種置換的,其中每個字符指數映射到一個新的地方範圍[0, textLength[
爲了做到這一點,你必須編寫自定義模量的Mod
運算符的餘數大於模數(從數學的角度來看,關於如何處理負數)
因此,您只需要遍歷字符串索引並將每個字符串索引映射到其「長度」模值的長度的文字
' Can be made local to Shift method if needed
Function Modulus(dividend As Integer, divisor As Integer) As Integer
dividend = dividend Mod divisor
Return If(dividend < 0, dividend + divisor, dividend)
End Function
Function Shift(text As String, offset As Integer) As String
' validation omitted
Dim length = text.Length
Dim arr(length - 1) As Char
For i = 0 To length - 1
arr(Modulus(i + offset, length) Mod length) = text(i)
Next
Return new String(arr)
End Function
通過這種方式,您可以輕鬆處理負值或大於文本長度的值。
請注意,使用StringBuilder
代替陣列也是一樣的;我不確定哪一個是「更好」
Function Shift(text As String, offset As Integer) As String
Dim builder As New StringBuilder(text)
Dim length = text.Length
For i = 0 To length - 1
builder(Modulus(i + offset, length) Mod length) = text(i)
Next
Return builder.ToString
End Function
什麼應該發生,如果量如果大於文字的長度? – Sehnsucht