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

C#如何移除字符串全部空白字符但保留双引号内部的空白?

C# 字符串空白过滤(保留双引号内空白)实现方案

核心需求:移除字符串中所有空白字符,但保留双引号包裹范围内的所有空白内容。

输入示例:"Stackoverflow is a very \"helpful website to\" use"
期望输出:"Stackoverflowisavery\"helpful website to\"use"

方案1:状态机遍历实现(推荐,性能更高)

适合处理长字符串,内存占用和执行效率都更优:

using System;
using System.Text;

public static class StringProcessor
{
    public static string RemoveWhitespaceKeepQuotedContent(string input)
    {
        if (string.IsNullOrEmpty(input))
            return input;
        
        StringBuilder resultBuilder = new StringBuilder(input.Length);
        // 标记当前是否处于双引号包裹范围内
        bool isInQuotes = false;
        
        foreach (char currentChar in input)
        {
            // 遇到双引号切换标记位,双引号本身直接保留
            if (currentChar == '"')
            {
                isInQuotes = !isInQuotes;
                resultBuilder.Append(currentChar);
                continue;
            }
            
            // 不在引号范围内的空白字符直接跳过
            if (!isInQuotes && char.IsWhiteSpace(currentChar))
                continue;
            
            // 其余字符正常追加
            resultBuilder.Append(currentChar);
        }

        return resultBuilder.ToString();
    }
}

方案2:正则表达式实现(代码更简洁)

适合短字符串处理,代码量更少无需手动维护状态:

using System.Text.RegularExpressions;

public static string RemoveWhitespaceKeepQuotedContentRegex(string input)
{
    // 正则逻辑:优先匹配双引号包裹的内容直接保留,其余空白字符替换为空
    return Regex.Replace(input, @"(""[^""]*"")|\s+", match => 
        match.Groups[1].Success ? match.Groups[1].Value : string.Empty);
}

调用测试

// 测试代码
string originalStr = "Stackoverflow is a very \"helpful website to\" use";
string processedStr = StringProcessor.RemoveWhitespaceKeepQuotedContent(originalStr);
Console.WriteLine(processedStr);
// 输出结果:Stackoverflowisavery"helpful website to"use

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:45:08