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

使用Ruby将文件中的Unicode转义序列转换为字符

问题:解析Unicode转义序列生成标准C++代码

我的code.txt文件中有一段包含Unicode转义序列的字符串,内容如下:

"class Solution {\u000Apublic:\u000A    vector\u003Cvector\u003Cint\u003E\u003E insert(vector\u003Cvector\u003Cint\u003E\u003E\u0026 intervals, vector\u003Cint\u003E\u0026 newInterval) {\u000A        int len \u003D intervals.size()\u003B\u000A        int index \u003D 0\u003B\u000A        vector\u003Cvector\u003Cint\u003E \u003E ans\u003B\u000A        \u000A\u000A        while(index \u003C len \u0026\u0026 intervals[index][1] \u003C newInterval[0]) ans.push_back(intervals[index++])\u003B\u000A        \u000A        while(index \u003C len \u0026\u0026 intervals[index][0] \u003C\u003D newInterval[1]) {\u000A            newInterval[0] \u003D min(intervals[index][0], newInterval[0])\u003B\u000A            newInterval[1] \u003D max(intervals[index][1], newInterval[1])\u003B\u000A            index++\u003B\u000A        }\u000A        \u000A        ans.push_back(newInterval)\u003B\u000A        \u000A        while(index \u003C len) ans.push_back(intervals[index++])\u003B\u000A\u000A        return ans\u003B \u000A    }\u000A}\u003B                         "

我需要将这段字符串转换为标准C++语法并写入solution.cpp,目标内容如下:

class Solution {
public:
    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
        int len = intervals.size();
        int index = 0;
        vector<vector<int> > ans;
        

        while(index < len && intervals[index][1] < newInterval[0]) ans.push_back(intervals[index++]);
        
        while(index < len && intervals[index][0] <= newInterval[1]) {
            newInterval[0] = min(intervals[index][0], newInterval[0]);
            newInterval[1] = max(intervals[index][1], newInterval[1]);
            index++;
        }
        
        ans.push_back(newInterval);
        
        while(index < len) ans.push_back(intervals[index++]);

        return ans; 
    }
};       

我尝试过用Ruby转换编码为UTF-8,但字符串没有变化,代码如下:

code = File.read('code.txt')
code = code.encode('UTF-8')
file = File.open('solution.cpp', "w:UTF-8")
file.write(code)

请问该如何实现需求?


解决方案

你之前的问题在于encode('UTF-8')只是转换字符串的编码格式,并不会解析字符串中的Unicode转义序列(如\u000A、\u003C)。要处理这类转义,可利用Ruby的JSON解析能力,因为你的字符串是标准的JSON格式(被双引号包裹,转义符符合JSON规范)。

修改后的Ruby代码如下:

require 'json'

# 读取文件内容并去除首尾多余的空格和引号
raw_code = File.read('code.txt').strip
# 用JSON解析自动处理Unicode转义序列
parsed_code = JSON.parse(raw_code)
# 将解析后的代码写入目标文件
File.write('solution.cpp', parsed_code)

说明:

  1. JSON.parse的作用:它会自动识别并转换字符串中的\uXXXX转义序列为对应的字符,比如\u000A转为换行符,\u003C转为<,\u003D转为=,\u0026转为&,完全符合你需要的标准C++代码格式。
  2. strip的作用:如果原文件中字符串首尾有多余的空格或换行,strip可以清除这些干扰,确保JSON解析能正常工作。

运行这段代码后,生成的solution.cpp就会和你期望的目标内容一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:01:25