实现对一个字符串的处理,首先将该字符串首尾的空格去掉,如果字符串中间还有连续空格的话,仅保留一个空格,即允许字符串中间有多个空格,但连续的空格数不可超过一个

C# 实现字符串空格规范化处理

这里提供几种 C# 的实现方式,从简洁到高效都有:

方法一:使用正则表达式(推荐)

using System;
using System.Text.RegularExpressions;

public class StringHelper
{
    public static string NormalizeSpaces(string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return string.Empty;
        
        // 去掉首尾空格,将中间连续空格替换为单个空格
        return Regex.Replace(text.Trim(), @"\s+", " ");
    }
}

// 使用示例
class Program
{
    static void Main()
    {
        string s = "  hello    world   C#  programming  ";
        string result = StringHelper.NormalizeSpaces(s);
        Console.WriteLine($"'{result}'");  // 输出: 'hello world C# programming'
    }
}

方法二:使用 Split + Join(最简洁)

using System;
using System.Linq;

public class StringHelper
{
    public static string NormalizeSpaces(string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return string.Empty;
        
        // Split 默认会去除空项,自动处理连续空格
        var words = text.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        return string.Join(" ", words);
    }
}

// 使用示例
class Program
{
    static void Main()
    {
        string s = "  hello    world   C#  programming  ";
        string result = StringHelper.NormalizeSpaces(s);
        Console.WriteLine($"'{result}'");  // 输出: 'hello world C# programming'
    }
}

方法三:使用 StringBuilder 手动遍历(性能最优)

using System;
using System.Text;

public class StringHelper
{
    public static string NormalizeSpaces(string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return string.Empty;
        
        // 先去掉首尾空格
        text = text.Trim();
        if (text.Length == 0)
            return string.Empty;
        
        StringBuilder result = new StringBuilder();
        bool previousIsSpace = false;
        
        foreach (char c in text)
        {
            if (c == ' ')
            {
                if (!previousIsSpace)
                {
                    result.Append(c);
                    previousIsSpace = true;
                }
            }
            else
            {
                result.Append(c);
                previousIsSpace = false;
            }
        }
        
        return result.ToString();
    }
}

// 使用示例
class Program
{
    static void Main()
    {
        string s = "  hello    world   C#  programming  ";
        string result = StringHelper.NormalizeSpaces(s);
        Console.WriteLine($"'{result}'");  // 输出: 'hello world C# programming'
    }
}

方法四:扩展方法(优雅调用)

using System;
using System.Text;
using System.Text.RegularExpressions;

public static class StringExtensions
{
    /// <summary>
    /// 去掉首尾空格,并将中间连续空格合并为单个空格
    /// </summary>
    public static string NormalizeSpaces(this string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return string.Empty;
        
        return Regex.Replace(text.Trim(), @"\s+", " ");
    }
    
    /// <summary>
    /// 去掉首尾空格,并将中间连续空格合并为单个空格(高性能版本)
    /// </summary>
    public static string NormalizeSpacesFast(this string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return string.Empty;
        
        text = text.Trim();
        if (text.Length == 0)
            return string.Empty;
        
        StringBuilder result = new StringBuilder();
        bool previousIsSpace = false;
        
        foreach (char c in text)
        {
            if (c == ' ')
            {
                if (!previousIsSpace)
                {
                    result.Append(c);
                    previousIsSpace = true;
                }
            }
            else
            {
                result.Append(c);
                previousIsSpace = false;
            }
        }
        
        return result.ToString();
    }
}

// 使用示例
class Program
{
    static void Main()
    {
        string s = "  hello    world   C#  programming  ";
        
        // 像调用实例方法一样使用
        string result = s.NormalizeSpaces();
        Console.WriteLine($"'{result}'");  // 输出: 'hello world C# programming'
        
        // 或使用高性能版本
        string resultFast = s.NormalizeSpacesFast();
        Console.WriteLine($"'{resultFast}'");  // 输出: 'hello world C# programming'
    }
}

方法五:处理所有空白字符(不仅仅是空格)

using System;
using System.Text;
using System.Text.RegularExpressions;

public static class StringExtensions
{
    /// <summary>
    /// 去掉首尾空白字符,并将中间连续空白字符(空格、Tab、换行等)替换为单个空格
    /// </summary>
    public static string NormalizeWhitespace(this string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return string.Empty;
        
        // 使用 \s 匹配所有空白字符
        return Regex.Replace(text.Trim(), @"\s+", " ");
    }
    
    /// <summary>
    /// 高性能版本:手动处理所有空白字符
    /// </summary>
    public static string NormalizeWhitespaceFast(this string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return string.Empty;
        
        text = text.Trim();
        if (text.Length == 0)
            return string.Empty;
        
        StringBuilder result = new StringBuilder();
        bool previousIsWhitespace = false;
        
        foreach (char c in text)
        {
            bool isWhitespace = char.IsWhiteSpace(c);
            
            if (isWhitespace)
            {
                if (!previousIsWhitespace)
                {
                    result.Append(' ');  // 统一替换为空格
                    previousIsWhitespace = true;
                }
            }
            else
            {
                result.Append(c);
                previousIsWhitespace = false;
            }
        }
        
        return result.ToString();
    }
}

// 使用示例
class Program
{
    static void Main()
    {
        // 包含 Tab、换行等空白字符
        string s = "  hello\t\tworld\n\nC#\r\nprogramming  ";
        
        string result = s.NormalizeWhitespace();
        Console.WriteLine($"'{result}'");  
        // 输出: 'hello world C# programming'
        
        string resultFast = s.NormalizeWhitespaceFast();
        Console.WriteLine($"'{resultFast}'");  
        // 输出: 'hello world C# programming'
    }
}

完整测试代码

using System;
using System.Text.RegularExpressions;

public class StringNormalizer
{
    // 方法1:正则表达式
    public static string Method1_Regex(string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return string.Empty;
        return Regex.Replace(text.Trim(), @"\s+", " ");
    }
    
    // 方法2:Split + Join
    public static string Method2_SplitJoin(string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return string.Empty;
        
        var words = text.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        return string.Join(" ", words);
    }
    
    // 方法3:手动遍历
    public static string Method3_Manual(string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return string.Empty;
        
        text = text.Trim();
        if (text.Length == 0)
            return string.Empty;
        
        System.Text.StringBuilder result = new System.Text.StringBuilder();
        bool prevIsSpace = false;
        
        foreach (char c in text)
        {
            if (c == ' ')
            {
                if (!prevIsSpace)
                {
                    result.Append(c);
                    prevIsSpace = true;
                }
            }
            else
            {
                result.Append(c);
                prevIsSpace = false;
            }
        }
        
        return result.ToString();
    }
}

class Program
{
    static void Main()
    {
        string[] testCases = new string[]
        {
            "  hello    world   C#  programming  ",
            "no extra spaces",
            "  leading and trailing  ",
            "multiple    spaces    between    words",
            "\t\thello\t\tworld\n\n",
            "   ",
            ""  // 空字符串
        };
        
        Console.WriteLine("字符串空格规范化测试\n");
        Console.WriteLine("方法1(正则) | 方法2(SplitJoin) | 方法3(手动)");
        Console.WriteLine(new string('-', 60));
        
        foreach (var test in testCases)
        {
            string result1 = StringNormalizer.Method1_Regex(test);
            string result2 = StringNormalizer.Method2_SplitJoin(test);
            string result3 = StringNormalizer.Method3_Manual(test);
            
            Console.WriteLine($"原字符串: '{test}'");
            Console.WriteLine($"方法1:    '{result1}'");
            Console.WriteLine($"方法2:    '{result2}'");
            Console.WriteLine($"方法3:    '{result3}'");
            Console.WriteLine(new string('-', 60));
        }
        
        // 性能测试(处理100万次)
        Console.WriteLine("\n性能测试(处理100万次):");
        string sample = "  hello    world   C#  programming  ";
        
        var sw = System.Diagnostics.Stopwatch.StartNew();
        for (int i = 0; i < 1_000_000; i++)
        {
            StringNormalizer.Method1_Regex(sample);
        }
        sw.Stop();
        Console.WriteLine($"正则表达式: {sw.ElapsedMilliseconds} ms");
        
        sw.Restart();
        for (int i = 0; i < 1_000_000; i++)
        {
            StringNormalizer.Method2_SplitJoin(sample);
        }
        sw.Stop();
        Console.WriteLine($"Split+Join: {sw.ElapsedMilliseconds} ms");
        
        sw.Restart();
        for (int i = 0; i < 1_000_000; i++)
        {
            StringNormalizer.Method3_Manual(sample);
        }
        sw.Stop();
        Console.WriteLine($"手动遍历:   {sw.ElapsedMilliseconds} ms");
    }
}

各方法对比

方法优点缺点适用场景性能
正则表达式简洁、灵活、易读性能一般一般业务场景中等
Split + Join最简洁、易懂只处理空格,不处理Tab等纯空格场景中等
手动遍历性能最优、内存友好代码稍长高性能要求、大数据量最快
扩展方法调用优雅、可复用需要定义静态类项目级工具库取决于内部实现

推荐方案

对于大多数 C# 项目,推荐使用扩展方法 + 正则表达式

public static class StringExtensions
{
    public static string NormalizeSpaces(this string text)
    {
        return string.IsNullOrWhiteSpace(text) 
            ? string.Empty 
            : Regex.Replace(text.Trim(), @"\s+", " ");
    }
}

// 使用
string result = "  hello    world   ".NormalizeSpaces();

如果使用 .NET 8+,还可以考虑使用 SearchValues 进一步优化性能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦幻南瓜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值