當您面對基本字母數字表無法處理的字符串時,會出現一個大問題。包含以下字詞的字符串: 「Déja vu
」 - >「é」將會是什麼?
而且,如果您使用.ToUpper()
,那麼如何編碼字符串「我是亞倫姆比利貝」。
.ToUpper返回「我是AARONMBILÉBÉ」。
你已經失去了外殼,你如何處理「É」的轉移?
當然,代碼應該像上面指出的那樣聰明,我只是通過使用System.Text.ASCIIEncoding
來簡化處理。但從我開始使用大量的文本數據,網絡資源,文件(...)我不得不深入挖掘,以及編碼和解碼字符串時,認真考慮字符串編碼(和系統字節序的方式,向/從字節數組)
重新想起了什麼,你真的想在做結束。如果你是唯一使用你的代碼的人,並且你確定你只會使用A..Z,0..9,a..z,空格和固定數量的允許字符(比如puntuation)那麼,只需構建一個包含每個字符的表。
Private _AllowedChars As Char() = { "A"c, "B"c, ... "0"c, "1"c, .. "."c, ","c ... }
或
Private _AllowedChars As Char() = "ABCDEF....012...abcd..xyz.;,?:/".ToCharArray()
然後使用
Private Function ShiftChars(ByVal CurrentString As String, ByVal ShiftValue As Integer) As String
Dim AllChars As Char() = CurrentString.ToCharArray()
Dim FinalChars As Char()
Dim i As Integer
FinalChars = New Char(AllChars.Length - 1) {} ' It's VB : UpperBound is n+1 item.
' so n items is UpperBound - 1
For i = 0 To AllChars.Length - 1
FinalChars(i) = _AllowedChars((Array.IndexOf(_AllowedChars, AllChars(i)) + ShiftValue) Mod _AllowedChars.Length)
Next
Return New String(FinalChars)
End Function
而且
Private Function UnShiftChars(ByVal CurrentString As String, ByVal ShiftValue As Integer) As String
' ... the same code until :
FinalChars(i) = _AllowedChars((Array.IndexOf(_AllowedChars, AllChars(i)) - ShiftValue + _AllowedChars.Length) Mod _AllowedChars.Length)
' ...
End Function
^^假設ShiftValue總是正的(定義一次)
但是,只有當您有一組預定義的允許字符時,這才起作用。如果你想要一個更靈活的工具,你應該開始處理編碼,字節數組,BitConverter,並看看系統的字節順序。這就是爲什麼我問,如果有人在goind使用你的應用程序:讓我們試試這個字符串:
"Xin chào thế giới" ' which is Hello World in vietnamese (Google Trad)
在這種情況下,你可能放棄..?不!你永遠都有一招! >得到字符串編碼(移)
Private Function ShiftChars(ByVal CurrentString As String, ByVal ShiftValue As Integer) As String
Dim AllChars As Char() = CurrentString.ToCharArray()
Dim FinalChars As Char()
Dim i As Integer
' Build your list of allowed chars...
_AllowedChars.Clear()
For i = 0 To AllChars.Length - 1
If Not _AllowedChars.ContainsKey(AllChars(i)) Then
_AllowedChars.Add(AllChars(i), AllChars(i))
End If
Next
' Then, encode...
FinalChars = New Char(AllChars.Length - 1) {}
For i = 0 To AllChars.Length - 1
FinalChars(i) = _AllowedChars.Keys.Item((_AllowedChars.IndexOfKey(AllChars(i)) + ShiftValue) Mod _AllowedChars.Count)
Next
Return New String(FinalChars)
End Function
同爲不印字/解碼 -
上飛
Private _AllowedChars As New SortedList(Of Char, Char)
只需創建您的允許字符。
注意:在外語中,結果字符串是純垃圾,並且完全不可讀,除非您再次移動字符。
但是,此變通辦法的主要侷限性與上述固定字符數組相同:一旦您對字符串進行了編碼,並且在您的編碼字符串中添加了一個不存在於最初生成的允許字符中的字符,你的數據已經固化了,你將無法解碼你的字符串。你所擁有的只是純粹的垃圾。
所以有一天......也許有一天,您需要在定義的擴展編碼(Unicode/UTF8/16)中深入挖掘事物的字節級別,以確保數據的完整性。