You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用.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 because substring returns 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 StringBuilder to efficiently build our encrypted/decrypted string (you could also concatenate strings directly, but StringBuilder is more efficient for loops).

Key Notes

  • Make sure your ORIGINAL_CHARS and REPLACEMENT_CHARS are 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:04:33