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

如何用System.IO方法替换文本文件中Name行的点为空格

Solution for Replacing Dots in Name Lines Only

Got it! Here's a clean solution that aligns with the System.IO.File.ReadAllLines and WriteAllLines approach you're already using:

using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
        string inputPath = "your-input-file.txt";
        string outputPath = "your-output-file.txt"; // Use same path to overwrite original

        // Read all lines from the input file
        string[] lines = File.ReadAllLines(inputPath);

        // Process each line: replace dots with spaces only in lines starting with "Name "
        string[] processedLines = lines.Select(line =>
        {
            if (line.StartsWith("Name "))
            {
                // Swap all dots in the Name line with spaces
                return line.Replace('.', ' ');
            }
            // Leave Number lines (and any other lines) untouched
            return line;
        }).ToArray();

        // Write the modified lines back to the file
        File.WriteAllLines(outputPath, processedLines);
    }
}

How It Works:

  • Reading Lines: File.ReadAllLines loads every line from your text file into a string array, making it simple to process each entry individually.
  • Line Processing:
    • We use LINQ's Select method to loop through each line.
    • For lines starting with Name , Replace('.', ' ') swaps every dot with a space—this ensures only Name-related lines get their dots replaced.
    • Lines starting with Number (or any other lines) stay exactly as they are, preserving their decimal points.
  • Writing Back: File.WriteAllLines saves the adjusted lines to your target file (you can use the input path directly to overwrite the original if that's what you need).

Optional Adjustment:

If you need to handle case-insensitive matches (like lines starting with name instead of Name ), update the StartsWith check to:

line.StartsWith("Name ", StringComparison.OrdinalIgnoreCase)

内容的提问来源于stack exchange,提问作者Tomas Nordström

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:30:03