''' <summary>
''' 字符串加密
''' </summary>
''' <param name="s">要加密的字符串</param>
''' <param name="n">加密移n位,正为右移,负为左移</param>
''' <returns>加密后的字符串</returns>
Function Encryption(s As String, n As Integer) As String
Dim c As String
Dim strL, i As Integer
'’处理n移位控制在 -25到25之间
n = n Mod 26
'’当n为负时处理成对应的正值 如-4,处理成 22
If n < 0 Then n += 26
'’初始值
Encryption = ""
'’原字符串的长度
strL = s.Length
i = 1
Do While i <= strL
'’取第i个位置的字符
c = Mid(s, i, 1)
''如果c在 大写字符范围,并且右移n位超出大写字符时
If (c >= "A" AndAlso c <= "Z") AndAlso Asc(c) + n > Asc("Z") Then
c = Chr(Asc(c) + n - 26)
ElseIf (c >= "A" AndAlso c <= "Z") Then ''在大写范围内时,并且右移n位不超出大写字符时
c = Chr(Asc(c) + n)
End If
If (c >= "a" AndAlso c <= "z") AndAlso Asc(c) + n > Asc("z") Then
c = Chr(Asc(c) + n - 26)
ElseIf (c >= "a" AndAlso c <= "z") Then
c = Chr(Asc(c) + n)
End If
Encryption &= c
i += 1
Loop
End Function
Sub Main()
Dim s As String = "world" ''原内容
Dim s1 As String = Encryption(s, 4) ''加密后的内容
Dim s2 As String = Encryption(s1, -4) '’解密后的内容
Console.WriteLine(s) '’显示原内容
Console.WriteLine(s1) '’显示加密后的内容
Console.WriteLine(s2) '’显示解密后的内容
Console.Read()
End Sub
world
asvph
world