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

Java实现:将含ASCII值的字符串还原为原字符串(如T104a110k115转回Thanks)

Reverse the ASCII-Transformed String Back to "Thanks"

Got it, let's break down how to reverse this conversion step by step. First, let's recap what your original code did: it took the original string Thanks, kept characters at even indices (0, 2, 4) as-is, and replaced characters at odd indices (1, 3, 5) with their ASCII integer values. So the transformed string T104a110k115 is made by interleaving original even-indexed chars with the ASCII numbers of the odd-indexed ones.

The Reverse Logic

To get back to Thanks, we need to:

  • Traverse the transformed string in consistent chunks: each chunk starts with an original character, followed by the 3-digit ASCII value of the corresponding odd-indexed character (since lowercase letters have 3-digit ASCII values, e.g., 'h' = 104, 'n' = 110).
  • For each chunk, extract the original character, convert the ASCII digits back to a char, and append both to our result.

Java Code to Restore the Original String

public class RestoreOriginalString {
    public static void main(String[] args) {
        String transformedStr = "T104a110k115";
        StringBuilder originalSb = new StringBuilder();
        
        // Each cycle is 1 original char + 3 ASCII digits (total 4 characters)
        for (int i = 0; i < transformedStr.length(); i += 4) {
            // Add the original even-indexed character
            originalSb.append(transformedStr.charAt(i));
            
            // Extract and convert the ASCII value back to a char
            String asciiNumStr = transformedStr.substring(i + 1, i + 4);
            int asciiValue = Integer.parseInt(asciiNumStr);
            originalSb.append((char) asciiValue);
        }
        
        String originalStr = originalSb.toString();
        System.out.println("Restored string: " + originalStr); // Outputs "Thanks"
    }
}

How This Works

  • The loop increments by 4 each time because each segment of the transformed string is 1 character + 3 digits (4 total characters per pair from the original string).
  • transformedStr.charAt(i) grabs the original even-indexed character (like 'T', 'a', 'k' from "Thanks").
  • substring(i+1, i+4) extracts the 3-digit ASCII string, which we parse to an integer and cast back to a char (turning 104 into 'h', 110 into 'n', etc.).

内容的提问来源于stack exchange,提问作者Code X

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:10:13