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

C#:如何按一个或多个空格/换行符分割数字序列字符串?

解决方案

方法1:读取全部内容后按空白序列分割

不要逐行读取后拼接内容(会丢失换行符导致数字粘连),直接用StreamReader.ReadToEnd()读取完整文本,再通过正则匹配任意空白序列完成分割:

using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

class NumberParser
{
    static void Main()
    {
        using (StreamReader sr = new StreamReader("你的文件路径.txt"))
        {
            // 一次性读取所有内容,保留原始换行和空格
            string fullContent = sr.ReadToEnd();
            
            // 用正则匹配一个或多个空白字符(空格、换行、回车等)作为分隔符
            string[] numberStrings = Regex.Split(fullContent, @"\s+")
                                          .Where(s => !string.IsNullOrWhiteSpace(s))
                                          .ToArray();
            
            // 可选:转换为数值类型
            double[] numbers = Array.ConvertAll(numberStrings, double.Parse);
            
            // 输出验证
            foreach (double num in numbers)
            {
                Console.WriteLine(num);
            }
        }
    }
}

方法2:直接提取所有符合格式的数字

如果数字格式固定(比如示例中的x.xx小数),可以直接用正则匹配提取数字,这种方式更鲁棒,不受分隔符类型影响:

using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

class NumberParser
{
    static void Main()
    {
        using (StreamReader sr = new StreamReader("你的文件路径.txt"))
        {
            string fullContent = sr.ReadToEnd();
            
            // 匹配所有小数格式的数字(支持整数和小数,比如123或123.45)
            MatchCollection matches = Regex.Matches(fullContent, @"\d+(?:\.\d+)?");
            string[] numberStrings = matches.Cast<Match>().Select(m => m.Value).ToArray();
            
            // 转换为数值类型
            double[] numbers = Array.ConvertAll(numberStrings, double.Parse);
            
            foreach (double num in numbers)
            {
                Console.WriteLine(num);
            }
        }
    }
}

为什么之前的方法失效

  1. 逐行读取后拼接会丢失换行符,导致原本被换行分隔的数字直接粘连(比如11.00和12.00变成11.0012.00),无法被分割。
  2. line.Split(' ', '\n')中,ReadLine()返回的行已经去掉了换行符,所以\n无法匹配;同时单个字符分割会把多个空格拆分成多个分隔符,产生空字符串。
  3. Regex.Split(line, @" +|\n")同样因为行内无换行符,\n匹配失效,只能处理空格分隔的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 21:53:10