如何不使用.replace()方法替换字符串字符并实现加密解密?
Hey there! I totally get your frustration—having to implement character replacement without relying on .replace() feels tricky at first, especially when restricted to just .indexOf(), .length(), and .substring(). Let's walk through exactly how to make this work, using your "Apple" → "&**$#" example as a guide.
The Core Idea
Instead of using a built-in replace method, we'll create a one-to-one mapping between your original characters and their encrypted symbols. We'll then iterate over each character in the input string, find its position in the original character set, and use that position to grab the corresponding symbol from our replacement set.
Step-by-Step Implementation (Java Example)
Since you mentioned methods like .length() (with parentheses), I'll use Java for the example—this logic translates easily to other languages with similar string methods too.
1. Define Your Character Mappings
First, create two strings: one for the original characters you want to replace, and another for their corresponding encrypted symbols. The positions of characters in these strings must match exactly (e.g., the 0th character in the original set maps to the 0th character in the replacement set).
public class MessageCipher { // Original character set (adjust this to include all characters you need to handle) private static final String ORIGINAL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // Replacement symbols: each position matches the character in ORIGINAL_CHARS // For your example: A → &, e → #, l → $, p → * private static final String REPLACEMENT_CHARS = "&*****************************$#************************"; // Encryption method public static String encrypt(String input) { StringBuilder encryptedResult = new StringBuilder(); // Iterate over each character in the input string for (int i = 0; i < input.length(); i++) { char currentChar = input.charAt(i); // Find the index of the current character in our original set int charIndex = ORIGINAL_CHARS.indexOf(currentChar); if (charIndex != -1) { // Use substring to get the matching replacement symbol // substring(startIndex, endIndex) is left-closed, right-open, so we take charIndex to charIndex+1 String replacement = REPLACEMENT_CHARS.substring(charIndex, charIndex + 1); encryptedResult.append(replacement); } else { // If the character isn't in our set (e.g., spaces, numbers), keep it as-is encryptedResult.append(currentChar); } } return encryptedResult.toString(); } // Decryption method (reverse the mapping) public static String decrypt(String input) { StringBuilder decryptedResult = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char currentChar = input.charAt(i); // Find the index of the symbol in our replacement set int symbolIndex = REPLACEMENT_CHARS.indexOf(currentChar); if (symbolIndex != -1) { // Grab the original character using the same index String originalChar = ORIGINAL_CHARS.substring(symbolIndex, symbolIndex + 1); decryptedResult.append(originalChar); } else { decryptedResult.append(currentChar); } } return decryptedResult.toString(); } // Test with your example public static void main(String[] args) { String testInput = "Apple"; String encrypted = encrypt(testInput); System.out.println("Encrypted: " + encrypted); // Outputs: &**$# String decrypted = decrypt(encrypted); System.out.println("Decrypted: " + decrypted); // Outputs: Apple } }
2. How It Works
- Iteration: We loop through each character in the input string using
input.length()to know how many times to run the loop. - Index Lookup:
ORIGINAL_CHARS.indexOf(currentChar)tells us where the current character lives in our original set. If it returns-1, the character isn't in our set and we leave it alone. - Symbol Retrieval: For characters that are in our set, we use
substring(charIndex, charIndex + 1)to pull the exact matching symbol from the replacement set. This works becausesubstringreturns the characters between the start and end indices (exclusive of the end index), so this gives us a single character. - Building the Result: We use a
StringBuilderto efficiently build our encrypted/decrypted string (you could also concatenate strings directly, butStringBuilderis more efficient for loops).
Key Notes
- Make sure your
ORIGINAL_CHARSandREPLACEMENT_CHARSare the same length—otherwise, you'll run into index errors for characters near the end. - Adjust the character sets to include any other characters you need to handle (e.g., numbers, punctuation) by adding them to both strings in the same position.
- This logic works for any mapping, not just your example—you can swap out the replacement symbols for any characters you want.
内容的提问来源于stack exchange,提问作者Blue Holliday

