如何用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.ReadAllLinesloads every line from your text file into a string array, making it simple to process each entry individually. - Line Processing:
- We use LINQ's
Selectmethod 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.
- We use LINQ's
- Writing Back:
File.WriteAllLinessaves 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
相关产品推荐
相关产品推荐

