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 进一步优化性能。

2545

被折叠的 条评论
为什么被折叠?



