VB.NET凯撒密码程序适配大小写字符及代码优化咨询
Hey there! Nice start on your Caesar Cipher assignment—getting the lowercase version working is a solid foundation. Let's adjust your code to handle both uppercase and lowercase letters, plus clean it up to be more efficient and readable.
1. Modification to Support Uppercase & Lowercase Letters
The main issue with your current code is that converting the entire input to lowercase (Frase = Trim(Frase.ToLower)) discards all uppercase information. Instead, we’ll check each character individually to see if it’s uppercase, lowercase, or a non-letter (like space), then apply the shift logic tailored to its type.
Here’s the core logic we’ll use:
- For uppercase letters (ASCII 65-90): After shifting, if we exceed 90 (Z), wrap around to the start of the uppercase range (A=65).
- For lowercase letters (ASCII 97-122): After shifting, if we exceed 122 (z), wrap around to the start of the lowercase range (a=97).
- For non-letters (spaces, symbols, numbers), leave them unchanged.
2. Optimized Code with Explanations
Let’s rewrite your code with these changes plus practical improvements:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click ' Get input text with basic validation Dim inputText As String = InputBox("Enter your text: ") If String.IsNullOrWhiteSpace(inputText) Then MsgBox("Please enter valid text!") Return End If ' Get shift amount and validate it's an integer Dim shiftAmount As Integer If Not Integer.TryParse(InputBox("Enter shift number (N): "), shiftAmount) Then MsgBox("Please enter a valid whole number for the shift!") Return End If ' Use StringBuilder for efficient string building (avoids redundant string copies) Dim resultBuilder As New System.Text.StringBuilder() ' Iterate over each character directly (more readable than index-based loops) For Each c As Char In inputText Dim charCode As Integer = Asc(c) ' Handle uppercase letters (A-Z) If Char.IsUpper(c) Then charCode += shiftAmount ' Wrap around if we go beyond Z While charCode > 90 charCode = 64 + (charCode - 90) End While ' Handle negative shifts (for decryption, if needed) While charCode < 65 charCode = 91 - (65 - charCode) End While resultBuilder.Append(Chr(charCode)) ' Handle lowercase letters (a-z) ElseIf Char.IsLower(c) Then charCode += shiftAmount ' Wrap around if we go beyond z While charCode > 122 charCode = 96 + (charCode - 122) End While ' Handle negative shifts While charCode < 97 charCode = 123 - (97 - charCode) End While resultBuilder.Append(Chr(charCode)) ' Keep non-letter characters as-is Else resultBuilder.Append(c) End If Next ' Display the final encrypted text MsgBox("Encrypted text: " & resultBuilder.ToString()) End Sub
Key Improvements Breakdown
- Input Validation: We added checks to prevent crashes from empty text or non-numeric shift values—always a good practice for user-facing code.
- StringBuilder: Instead of concatenating strings with
&in a loop (which creates new string objects every time),StringBuilderbuilds the result efficiently in one place, especially helpful for longer texts. - For Each Loop: Iterating directly over each
Charin the input is more readable than usingMid()and index counters. - Char.IsUpper/IsLower: These built-in methods make the code easier to understand than checking ASCII values directly.
- Negative Shift Support: While your assignment might not require decryption, adding this makes the code flexible if you need to reverse the cipher later.
- Cleaner Variable Usage: We removed unused variables like
tempand simplified the logic flow.
Bonus: Simplify Wrap-Around with Modulo
If you want to replace the While loops with a more concise calculation, use modulo arithmetic. For example, for lowercase letters:
charCode = 97 + ((charCode - 97 + shiftAmount) Mod 26) ' Fix negative modulo results (VB.NET can return negative values here) If charCode < 97 Then charCode += 26
This does the same wrap-around logic in one line—feel free to swap this in for a tighter code style!
内容的提问来源于stack exchange,提问作者positive_tax000

