MST
星途 面试题库

面试题:C#字符串性能优化处理与正则表达式高级应用

假设你正在处理一个非常大的文本文件(可能有几百MB甚至更大),其中包含大量形如`{"id":"12345","name":"Some Name","value":"Some Value"}`这样的JSON格式字符串片段(每个片段独占一行)。使用C#编写代码实现:1. 高效读取文件内容,避免一次性加载整个文件到内存。2. 使用正则表达式验证每个JSON片段的格式是否正确,确保`id`是数字,`name`和`value`是非空字符串。3. 对于格式正确的JSON片段,提取`id`、`name`和`value`,存储到一个`Dictionary<string, Dictionary<string, string>>`中,其中外层字典的键是`id`,内层字典包含`name`和`value`的键值对。同时,要考虑代码的性能优化,尽量减少内存占用和处理时间。
33.0万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string filePath = "yourLargeFile.txt";
        var result = new Dictionary<string, Dictionary<string, string>>();

        using (StreamReader reader = new StreamReader(filePath))
        {
            string line;
            Regex jsonRegex = new Regex(@"^\{ ""id"":""(\d+)"", ""name"":""([^""]+)"", ""value"":""([^""]+)""\}$");
            while ((line = reader.ReadLine()) != null)
            {
                Match match = jsonRegex.Match(line);
                if (match.Success)
                {
                    string id = match.Groups[1].Value;
                    string name = match.Groups[2].Value;
                    string value = match.Groups[3].Value;

                    if (!result.ContainsKey(id))
                    {
                        result[id] = new Dictionary<string, string>();
                    }
                    result[id]["name"] = name;
                    result[id]["value"] = value;
                }
            }
        }

        // 打印结果验证
        foreach (var kvp in result)
        {
            Console.WriteLine($"Id: {kvp.Key}, Name: {kvp.Value["name"]}, Value: {kvp.Value["value"]}");
        }
    }
}
  1. 文件读取:使用StreamReader逐行读取文件,避免一次性加载整个文件到内存。
  2. 正则表达式验证:定义正则表达式^\{ ""id"":""(\d+)"", ""name"":""([^""]+)"", ""value"":""([^""]+)""\}$来验证JSON片段格式,确保id是数字,namevalue是非空字符串。
  3. 数据存储:使用Dictionary<string, Dictionary<string, string>>来存储提取的数据,外层字典键为id,内层字典包含namevalue的键值对。
  4. 性能优化:逐行读取和处理,减少内存占用,同时正则表达式预编译提高匹配效率。